blob: 256e8f6995161d5158565f06e671ab40b5232ca5 [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 Jahanian15f87772012-02-28 22:45:07 +0000112 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
244 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
310
311 // Expression Rewriting.
312 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
313 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
314 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
317 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
318 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000319 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000320 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000321 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000322 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
325 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
326 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
327 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
328 SourceLocation OrigEnd);
329 Stmt *RewriteBreakStmt(BreakStmt *S);
330 Stmt *RewriteContinueStmt(ContinueStmt *S);
331 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000332 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000333 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334
335 // Block rewriting.
336 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
337
338 // Block specific rewrite rules.
339 void RewriteBlockPointerDecl(NamedDecl *VD);
340 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000341 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
343 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
344
345 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000348 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
349
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000350 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
351
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000352 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
353 std::string &Result);
354
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 virtual void Initialize(ASTContext &context);
356
357 // Misc. AST transformation routines. Somtimes they end up calling
358 // rewriting routines on the new ASTs.
359 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
360 Expr **args, unsigned nargs,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 void SynthCountByEnumWithState(std::string &buf);
369 void SynthMsgSendFunctionDecl();
370 void SynthMsgSendSuperFunctionDecl();
371 void SynthMsgSendStretFunctionDecl();
372 void SynthMsgSendFpretFunctionDecl();
373 void SynthMsgSendSuperStretFunctionDecl();
374 void SynthGetClassFunctionDecl();
375 void SynthGetMetaClassFunctionDecl();
376 void SynthGetSuperClassFunctionDecl();
377 void SynthSelGetUidFunctionDecl();
378 void SynthSuperContructorFunctionDecl();
379
380 // Rewriting metadata
381 template<typename MethodIterator>
382 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
383 MethodIterator MethodEnd,
384 bool IsInstanceMethod,
385 StringRef prefix,
386 StringRef ClassName,
387 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000388 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
389 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000390 virtual void RewriteObjCProtocolListMetaData(
391 const ObjCList<ObjCProtocolDecl> &Prots,
392 StringRef prefix, StringRef ClassName, std::string &Result);
393 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
394 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000395 virtual void RewriteClassSetupInitHook(std::string &Result);
396
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000397 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000398 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000399 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
400 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000401 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000402
403 // Rewriting ivar
404 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
405 std::string &Result);
406 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
407
408
409 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
410 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
411 StringRef funcName, std::string Tag);
412 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
413 StringRef funcName, std::string Tag);
414 std::string SynthesizeBlockImpl(BlockExpr *CE,
415 std::string Tag, std::string Desc);
416 std::string SynthesizeBlockDescriptor(std::string DescTag,
417 std::string ImplTag,
418 int i, StringRef funcName,
419 unsigned hasCopy);
420 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
421 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
422 StringRef FunName);
423 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
424 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000425 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426
427 // Misc. helper routines.
428 QualType getProtocolType();
429 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
431 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
432 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
433
434 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
435 void CollectBlockDeclRefInfo(BlockExpr *Exp);
436 void GetBlockDeclRefExprs(Stmt *S);
437 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000438 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000439 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
440
441 // We avoid calling Type::isBlockPointerType(), since it operates on the
442 // canonical type. We only care if the top-level type is a closure pointer.
443 bool isTopLevelBlockPointerType(QualType T) {
444 return isa<BlockPointerType>(T);
445 }
446
447 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
448 /// to a function pointer type and upon success, returns true; false
449 /// otherwise.
450 bool convertBlockPointerToFunctionPointer(QualType &T) {
451 if (isTopLevelBlockPointerType(T)) {
452 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
453 T = Context->getPointerType(BPT->getPointeeType());
454 return true;
455 }
456 return false;
457 }
458
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000459 bool convertObjCTypeToCStyleType(QualType &T);
460
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461 bool needToScanForQualifiers(QualType T);
462 QualType getSuperStructType();
463 QualType getConstantStringStructType();
464 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
465 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
466
467 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000468 if (T->isObjCQualifiedIdType()) {
469 bool isConst = T.isConstQualified();
470 T = isConst ? Context->getObjCIdType().withConst()
471 : Context->getObjCIdType();
472 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000473 else if (T->isObjCQualifiedClassType())
474 T = Context->getObjCClassType();
475 else if (T->isObjCObjectPointerType() &&
476 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
477 if (const ObjCObjectPointerType * OBJPT =
478 T->getAsObjCInterfacePointerType()) {
479 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
480 T = QualType(IFaceT, 0);
481 T = Context->getPointerType(T);
482 }
483 }
484 }
485
486 // FIXME: This predicate seems like it would be useful to add to ASTContext.
487 bool isObjCType(QualType T) {
488 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
489 return false;
490
491 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
492
493 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
494 OCT == Context->getCanonicalType(Context->getObjCClassType()))
495 return true;
496
497 if (const PointerType *PT = OCT->getAs<PointerType>()) {
498 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
499 PT->getPointeeType()->isObjCQualifiedIdType())
500 return true;
501 }
502 return false;
503 }
504 bool PointerTypeTakesAnyBlockArguments(QualType QT);
505 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
506 void GetExtentOfArgList(const char *Name, const char *&LParen,
507 const char *&RParen);
508
509 void QuoteDoublequotes(std::string &From, std::string &To) {
510 for (unsigned i = 0; i < From.length(); i++) {
511 if (From[i] == '"')
512 To += "\\\"";
513 else
514 To += From[i];
515 }
516 }
517
518 QualType getSimpleFunctionType(QualType result,
519 const QualType *args,
520 unsigned numArgs,
521 bool variadic = false) {
522 if (result == Context->getObjCInstanceType())
523 result = Context->getObjCIdType();
524 FunctionProtoType::ExtProtoInfo fpi;
525 fpi.Variadic = variadic;
526 return Context->getFunctionType(result, args, numArgs, fpi);
527 }
528
529 // Helper function: create a CStyleCastExpr with trivial type source info.
530 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
531 CastKind Kind, Expr *E) {
532 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
533 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
534 SourceLocation(), SourceLocation());
535 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000536
537 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
538 IdentifierInfo* II = &Context->Idents.get("load");
539 Selector LoadSel = Context->Selectors.getSelector(0, &II);
540 return OD->getClassMethod(LoadSel) != 0;
541 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000542 };
543
544}
545
546void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
548 if (const FunctionProtoType *fproto
549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
550 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
551 E = fproto->arg_type_end(); I && (I != E); ++I)
552 if (isTopLevelBlockPointerType(*I)) {
553 // All the args are checked/rewritten. Don't call twice!
554 RewriteBlockPointerDecl(D);
555 break;
556 }
557 }
558}
559
560void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
561 const PointerType *PT = funcType->getAs<PointerType>();
562 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
563 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
564}
565
566static bool IsHeaderFile(const std::string &Filename) {
567 std::string::size_type DotPos = Filename.rfind('.');
568
569 if (DotPos == std::string::npos) {
570 // no file extension
571 return false;
572 }
573
574 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 // C header: .h
576 // C++ header: .hh or .H;
577 return Ext == "h" || Ext == "hh" || Ext == "H";
578}
579
580RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
581 DiagnosticsEngine &D, const LangOptions &LOpts,
582 bool silenceMacroWarn)
583 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
584 SilenceRewriteMacroWarning(silenceMacroWarn) {
585 IsHeader = IsHeaderFile(inFile);
586 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
587 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000588 // FIXME. This should be an error. But if block is not called, it is OK. And it
589 // may break including some headers.
590 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting block literal declared in global scope is not implemented");
592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000593 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
594 DiagnosticsEngine::Warning,
595 "rewriter doesn't support user-specified control flow semantics "
596 "for @try/@finally (code may not execute properly)");
597}
598
599ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
600 raw_ostream* OS,
601 DiagnosticsEngine &Diags,
602 const LangOptions &LOpts,
603 bool SilenceRewriteMacroWarning) {
604 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
605}
606
607void RewriteModernObjC::InitializeCommon(ASTContext &context) {
608 Context = &context;
609 SM = &Context->getSourceManager();
610 TUDecl = Context->getTranslationUnitDecl();
611 MsgSendFunctionDecl = 0;
612 MsgSendSuperFunctionDecl = 0;
613 MsgSendStretFunctionDecl = 0;
614 MsgSendSuperStretFunctionDecl = 0;
615 MsgSendFpretFunctionDecl = 0;
616 GetClassFunctionDecl = 0;
617 GetMetaClassFunctionDecl = 0;
618 GetSuperClassFunctionDecl = 0;
619 SelGetUidFunctionDecl = 0;
620 CFStringFunctionDecl = 0;
621 ConstantStringClassReference = 0;
622 NSStringRecord = 0;
623 CurMethodDef = 0;
624 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000625 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000626 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000627 SuperStructDecl = 0;
628 ProtocolTypeDecl = 0;
629 ConstantStringDecl = 0;
630 BcLabelCount = 0;
631 SuperContructorFunctionDecl = 0;
632 NumObjCStringLiterals = 0;
633 PropParentMap = 0;
634 CurrentBody = 0;
635 DisableReplaceStmt = false;
636 objc_impl_method = false;
637
638 // Get the ID and start/end of the main file.
639 MainFileID = SM->getMainFileID();
640 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
641 MainFileStart = MainBuf->getBufferStart();
642 MainFileEnd = MainBuf->getBufferEnd();
643
David Blaikie4e4d0842012-03-11 07:00:24 +0000644 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000645}
646
647//===----------------------------------------------------------------------===//
648// Top Level Driver Code
649//===----------------------------------------------------------------------===//
650
651void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
652 if (Diags.hasErrorOccurred())
653 return;
654
655 // Two cases: either the decl could be in the main file, or it could be in a
656 // #included file. If the former, rewrite it now. If the later, check to see
657 // if we rewrote the #include/#import.
658 SourceLocation Loc = D->getLocation();
659 Loc = SM->getExpansionLoc(Loc);
660
661 // If this is for a builtin, ignore it.
662 if (Loc.isInvalid()) return;
663
664 // Look for built-in declarations that we need to refer during the rewrite.
665 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
666 RewriteFunctionDecl(FD);
667 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
668 // declared in <Foundation/NSString.h>
669 if (FVD->getName() == "_NSConstantStringClassReference") {
670 ConstantStringClassReference = FVD;
671 return;
672 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000673 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
674 RewriteCategoryDecl(CD);
675 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
676 if (PD->isThisDeclarationADefinition())
677 RewriteProtocolDecl(PD);
678 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000679 // FIXME. This will not work in all situations and leaving it out
680 // is harmless.
681 // RewriteLinkageSpec(LSD);
682
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683 // Recurse into linkage specifications
684 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
685 DIEnd = LSD->decls_end();
686 DI != DIEnd; ) {
687 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
688 if (!IFace->isThisDeclarationADefinition()) {
689 SmallVector<Decl *, 8> DG;
690 SourceLocation StartLoc = IFace->getLocStart();
691 do {
692 if (isa<ObjCInterfaceDecl>(*DI) &&
693 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
694 StartLoc == (*DI)->getLocStart())
695 DG.push_back(*DI);
696 else
697 break;
698
699 ++DI;
700 } while (DI != DIEnd);
701 RewriteForwardClassDecl(DG);
702 continue;
703 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000704 else {
705 // Keep track of all interface declarations seen.
706 ObjCInterfacesSeen.push_back(IFace);
707 ++DI;
708 continue;
709 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000710 }
711
712 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
713 if (!Proto->isThisDeclarationADefinition()) {
714 SmallVector<Decl *, 8> DG;
715 SourceLocation StartLoc = Proto->getLocStart();
716 do {
717 if (isa<ObjCProtocolDecl>(*DI) &&
718 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
719 StartLoc == (*DI)->getLocStart())
720 DG.push_back(*DI);
721 else
722 break;
723
724 ++DI;
725 } while (DI != DIEnd);
726 RewriteForwardProtocolDecl(DG);
727 continue;
728 }
729 }
730
731 HandleTopLevelSingleDecl(*DI);
732 ++DI;
733 }
734 }
735 // If we have a decl in the main file, see if we should rewrite it.
736 if (SM->isFromMainFile(Loc))
737 return HandleDeclInMainFile(D);
738}
739
740//===----------------------------------------------------------------------===//
741// Syntactic (non-AST) Rewriting Code
742//===----------------------------------------------------------------------===//
743
744void RewriteModernObjC::RewriteInclude() {
745 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
746 StringRef MainBuf = SM->getBufferData(MainFileID);
747 const char *MainBufStart = MainBuf.begin();
748 const char *MainBufEnd = MainBuf.end();
749 size_t ImportLen = strlen("import");
750
751 // Loop over the whole file, looking for includes.
752 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
753 if (*BufPtr == '#') {
754 if (++BufPtr == MainBufEnd)
755 return;
756 while (*BufPtr == ' ' || *BufPtr == '\t')
757 if (++BufPtr == MainBufEnd)
758 return;
759 if (!strncmp(BufPtr, "import", ImportLen)) {
760 // replace import with include
761 SourceLocation ImportLoc =
762 LocStart.getLocWithOffset(BufPtr-MainBufStart);
763 ReplaceText(ImportLoc, ImportLen, "include");
764 BufPtr += ImportLen;
765 }
766 }
767 }
768}
769
770static std::string getIvarAccessString(ObjCIvarDecl *OID) {
771 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
772 std::string S;
773 S = "((struct ";
774 S += ClassDecl->getIdentifier()->getName();
775 S += "_IMPL *)self)->";
776 S += OID->getName();
777 return S;
778}
779
780void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
781 ObjCImplementationDecl *IMD,
782 ObjCCategoryImplDecl *CID) {
783 static bool objcGetPropertyDefined = false;
784 static bool objcSetPropertyDefined = false;
785 SourceLocation startLoc = PID->getLocStart();
786 InsertText(startLoc, "// ");
787 const char *startBuf = SM->getCharacterData(startLoc);
788 assert((*startBuf == '@') && "bogus @synthesize location");
789 const char *semiBuf = strchr(startBuf, ';');
790 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
791 SourceLocation onePastSemiLoc =
792 startLoc.getLocWithOffset(semiBuf-startBuf+1);
793
794 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
795 return; // FIXME: is this correct?
796
797 // Generate the 'getter' function.
798 ObjCPropertyDecl *PD = PID->getPropertyDecl();
799 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
800
801 if (!OID)
802 return;
803 unsigned Attributes = PD->getPropertyAttributes();
804 if (!PD->getGetterMethodDecl()->isDefined()) {
805 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
806 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
807 ObjCPropertyDecl::OBJC_PR_copy));
808 std::string Getr;
809 if (GenGetProperty && !objcGetPropertyDefined) {
810 objcGetPropertyDefined = true;
811 // FIXME. Is this attribute correct in all cases?
812 Getr = "\nextern \"C\" __declspec(dllimport) "
813 "id objc_getProperty(id, SEL, long, bool);\n";
814 }
815 RewriteObjCMethodDecl(OID->getContainingInterface(),
816 PD->getGetterMethodDecl(), Getr);
817 Getr += "{ ";
818 // Synthesize an explicit cast to gain access to the ivar.
819 // See objc-act.c:objc_synthesize_new_getter() for details.
820 if (GenGetProperty) {
821 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
822 Getr += "typedef ";
823 const FunctionType *FPRetType = 0;
824 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
825 FPRetType);
826 Getr += " _TYPE";
827 if (FPRetType) {
828 Getr += ")"; // close the precedence "scope" for "*".
829
830 // Now, emit the argument types (if any).
831 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
832 Getr += "(";
833 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
834 if (i) Getr += ", ";
835 std::string ParamStr = FT->getArgType(i).getAsString(
836 Context->getPrintingPolicy());
837 Getr += ParamStr;
838 }
839 if (FT->isVariadic()) {
840 if (FT->getNumArgs()) Getr += ", ";
841 Getr += "...";
842 }
843 Getr += ")";
844 } else
845 Getr += "()";
846 }
847 Getr += ";\n";
848 Getr += "return (_TYPE)";
849 Getr += "objc_getProperty(self, _cmd, ";
850 RewriteIvarOffsetComputation(OID, Getr);
851 Getr += ", 1)";
852 }
853 else
854 Getr += "return " + getIvarAccessString(OID);
855 Getr += "; }";
856 InsertText(onePastSemiLoc, Getr);
857 }
858
859 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
860 return;
861
862 // Generate the 'setter' function.
863 std::string Setr;
864 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
865 ObjCPropertyDecl::OBJC_PR_copy);
866 if (GenSetProperty && !objcSetPropertyDefined) {
867 objcSetPropertyDefined = true;
868 // FIXME. Is this attribute correct in all cases?
869 Setr = "\nextern \"C\" __declspec(dllimport) "
870 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
871 }
872
873 RewriteObjCMethodDecl(OID->getContainingInterface(),
874 PD->getSetterMethodDecl(), Setr);
875 Setr += "{ ";
876 // Synthesize an explicit cast to initialize the ivar.
877 // See objc-act.c:objc_synthesize_new_setter() for details.
878 if (GenSetProperty) {
879 Setr += "objc_setProperty (self, _cmd, ";
880 RewriteIvarOffsetComputation(OID, Setr);
881 Setr += ", (id)";
882 Setr += PD->getName();
883 Setr += ", ";
884 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
885 Setr += "0, ";
886 else
887 Setr += "1, ";
888 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
889 Setr += "1)";
890 else
891 Setr += "0)";
892 }
893 else {
894 Setr += getIvarAccessString(OID) + " = ";
895 Setr += PD->getName();
896 }
897 Setr += "; }";
898 InsertText(onePastSemiLoc, Setr);
899}
900
901static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
902 std::string &typedefString) {
903 typedefString += "#ifndef _REWRITER_typedef_";
904 typedefString += ForwardDecl->getNameAsString();
905 typedefString += "\n";
906 typedefString += "#define _REWRITER_typedef_";
907 typedefString += ForwardDecl->getNameAsString();
908 typedefString += "\n";
909 typedefString += "typedef struct objc_object ";
910 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000911 // typedef struct { } _objc_exc_Classname;
912 typedefString += ";\ntypedef struct {} _objc_exc_";
913 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000914 typedefString += ";\n#endif\n";
915}
916
917void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
918 const std::string &typedefString) {
919 SourceLocation startLoc = ClassDecl->getLocStart();
920 const char *startBuf = SM->getCharacterData(startLoc);
921 const char *semiPtr = strchr(startBuf, ';');
922 // Replace the @class with typedefs corresponding to the classes.
923 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
924}
925
926void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
927 std::string typedefString;
928 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
929 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
930 if (I == D.begin()) {
931 // Translate to typedef's that forward reference structs with the same name
932 // as the class. As a convenience, we include the original declaration
933 // as a comment.
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
940 DeclGroupRef::iterator I = D.begin();
941 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
942}
943
944void RewriteModernObjC::RewriteForwardClassDecl(
945 const llvm::SmallVector<Decl*, 8> &D) {
946 std::string typedefString;
947 for (unsigned i = 0; i < D.size(); i++) {
948 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
949 if (i == 0) {
950 typedefString += "// @class ";
951 typedefString += ForwardDecl->getNameAsString();
952 typedefString += ";\n";
953 }
954 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
955 }
956 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
957}
958
959void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
960 // When method is a synthesized one, such as a getter/setter there is
961 // nothing to rewrite.
962 if (Method->isImplicit())
963 return;
964 SourceLocation LocStart = Method->getLocStart();
965 SourceLocation LocEnd = Method->getLocEnd();
966
967 if (SM->getExpansionLineNumber(LocEnd) >
968 SM->getExpansionLineNumber(LocStart)) {
969 InsertText(LocStart, "#if 0\n");
970 ReplaceText(LocEnd, 1, ";\n#endif\n");
971 } else {
972 InsertText(LocStart, "// ");
973 }
974}
975
976void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
977 SourceLocation Loc = prop->getAtLoc();
978
979 ReplaceText(Loc, 0, "// ");
980 // FIXME: handle properties that are declared across multiple lines.
981}
982
983void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
984 SourceLocation LocStart = CatDecl->getLocStart();
985
986 // FIXME: handle category headers that are declared across multiple lines.
987 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000988 if (CatDecl->getIvarLBraceLoc().isValid())
989 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000990 for (ObjCCategoryDecl::ivar_iterator
991 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
992 ObjCIvarDecl *Ivar = (*I);
993 SourceLocation LocStart = Ivar->getLocStart();
994 ReplaceText(LocStart, 0, "// ");
995 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000996 if (CatDecl->getIvarRBraceLoc().isValid())
997 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000999 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1000 E = CatDecl->prop_end(); I != E; ++I)
1001 RewriteProperty(*I);
1002
1003 for (ObjCCategoryDecl::instmeth_iterator
1004 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1005 I != E; ++I)
1006 RewriteMethodDeclaration(*I);
1007 for (ObjCCategoryDecl::classmeth_iterator
1008 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1009 I != E; ++I)
1010 RewriteMethodDeclaration(*I);
1011
1012 // Lastly, comment out the @end.
1013 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1014 strlen("@end"), "/* @end */");
1015}
1016
1017void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1018 SourceLocation LocStart = PDecl->getLocStart();
1019 assert(PDecl->isThisDeclarationADefinition());
1020
1021 // FIXME: handle protocol headers that are declared across multiple lines.
1022 ReplaceText(LocStart, 0, "// ");
1023
1024 for (ObjCProtocolDecl::instmeth_iterator
1025 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1026 I != E; ++I)
1027 RewriteMethodDeclaration(*I);
1028 for (ObjCProtocolDecl::classmeth_iterator
1029 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1030 I != E; ++I)
1031 RewriteMethodDeclaration(*I);
1032
1033 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1034 E = PDecl->prop_end(); I != E; ++I)
1035 RewriteProperty(*I);
1036
1037 // Lastly, comment out the @end.
1038 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1039 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1040
1041 // Must comment out @optional/@required
1042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
1044 for (const char *p = startBuf; p < endBuf; p++) {
1045 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1046 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1047 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1048
1049 }
1050 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1051 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1052 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1053
1054 }
1055 }
1056}
1057
1058void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1059 SourceLocation LocStart = (*D.begin())->getLocStart();
1060 if (LocStart.isInvalid())
1061 llvm_unreachable("Invalid SourceLocation");
1062 // FIXME: handle forward protocol that are declared across multiple lines.
1063 ReplaceText(LocStart, 0, "// ");
1064}
1065
1066void
1067RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1068 SourceLocation LocStart = DG[0]->getLocStart();
1069 if (LocStart.isInvalid())
1070 llvm_unreachable("Invalid SourceLocation");
1071 // FIXME: handle forward protocol that are declared across multiple lines.
1072 ReplaceText(LocStart, 0, "// ");
1073}
1074
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001075void
1076RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1077 SourceLocation LocStart = LSD->getExternLoc();
1078 if (LocStart.isInvalid())
1079 llvm_unreachable("Invalid extern SourceLocation");
1080
1081 ReplaceText(LocStart, 0, "// ");
1082 if (!LSD->hasBraces())
1083 return;
1084 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1085 SourceLocation LocRBrace = LSD->getRBraceLoc();
1086 if (LocRBrace.isInvalid())
1087 llvm_unreachable("Invalid rbrace SourceLocation");
1088 ReplaceText(LocRBrace, 0, "// ");
1089}
1090
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001091void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1092 const FunctionType *&FPRetType) {
1093 if (T->isObjCQualifiedIdType())
1094 ResultStr += "id";
1095 else if (T->isFunctionPointerType() ||
1096 T->isBlockPointerType()) {
1097 // needs special handling, since pointer-to-functions have special
1098 // syntax (where a decaration models use).
1099 QualType retType = T;
1100 QualType PointeeTy;
1101 if (const PointerType* PT = retType->getAs<PointerType>())
1102 PointeeTy = PT->getPointeeType();
1103 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1104 PointeeTy = BPT->getPointeeType();
1105 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1106 ResultStr += FPRetType->getResultType().getAsString(
1107 Context->getPrintingPolicy());
1108 ResultStr += "(*";
1109 }
1110 } else
1111 ResultStr += T.getAsString(Context->getPrintingPolicy());
1112}
1113
1114void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1115 ObjCMethodDecl *OMD,
1116 std::string &ResultStr) {
1117 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1118 const FunctionType *FPRetType = 0;
1119 ResultStr += "\nstatic ";
1120 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1121 ResultStr += " ";
1122
1123 // Unique method name
1124 std::string NameStr;
1125
1126 if (OMD->isInstanceMethod())
1127 NameStr += "_I_";
1128 else
1129 NameStr += "_C_";
1130
1131 NameStr += IDecl->getNameAsString();
1132 NameStr += "_";
1133
1134 if (ObjCCategoryImplDecl *CID =
1135 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1136 NameStr += CID->getNameAsString();
1137 NameStr += "_";
1138 }
1139 // Append selector names, replacing ':' with '_'
1140 {
1141 std::string selString = OMD->getSelector().getAsString();
1142 int len = selString.size();
1143 for (int i = 0; i < len; i++)
1144 if (selString[i] == ':')
1145 selString[i] = '_';
1146 NameStr += selString;
1147 }
1148 // Remember this name for metadata emission
1149 MethodInternalNames[OMD] = NameStr;
1150 ResultStr += NameStr;
1151
1152 // Rewrite arguments
1153 ResultStr += "(";
1154
1155 // invisible arguments
1156 if (OMD->isInstanceMethod()) {
1157 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1158 selfTy = Context->getPointerType(selfTy);
1159 if (!LangOpts.MicrosoftExt) {
1160 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1161 ResultStr += "struct ";
1162 }
1163 // When rewriting for Microsoft, explicitly omit the structure name.
1164 ResultStr += IDecl->getNameAsString();
1165 ResultStr += " *";
1166 }
1167 else
1168 ResultStr += Context->getObjCClassType().getAsString(
1169 Context->getPrintingPolicy());
1170
1171 ResultStr += " self, ";
1172 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1173 ResultStr += " _cmd";
1174
1175 // Method arguments.
1176 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1177 E = OMD->param_end(); PI != E; ++PI) {
1178 ParmVarDecl *PDecl = *PI;
1179 ResultStr += ", ";
1180 if (PDecl->getType()->isObjCQualifiedIdType()) {
1181 ResultStr += "id ";
1182 ResultStr += PDecl->getNameAsString();
1183 } else {
1184 std::string Name = PDecl->getNameAsString();
1185 QualType QT = PDecl->getType();
1186 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001187 (void)convertBlockPointerToFunctionPointer(QT);
1188 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001189 ResultStr += Name;
1190 }
1191 }
1192 if (OMD->isVariadic())
1193 ResultStr += ", ...";
1194 ResultStr += ") ";
1195
1196 if (FPRetType) {
1197 ResultStr += ")"; // close the precedence "scope" for "*".
1198
1199 // Now, emit the argument types (if any).
1200 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1201 ResultStr += "(";
1202 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1203 if (i) ResultStr += ", ";
1204 std::string ParamStr = FT->getArgType(i).getAsString(
1205 Context->getPrintingPolicy());
1206 ResultStr += ParamStr;
1207 }
1208 if (FT->isVariadic()) {
1209 if (FT->getNumArgs()) ResultStr += ", ";
1210 ResultStr += "...";
1211 }
1212 ResultStr += ")";
1213 } else {
1214 ResultStr += "()";
1215 }
1216 }
1217}
1218void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1219 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1220 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1221
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001222 if (IMD) {
1223 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001224 if (IMD->getIvarLBraceLoc().isValid())
1225 InsertText(IMD->getIvarLBraceLoc(), "// ");
1226 for (ObjCImplementationDecl::ivar_iterator
1227 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1228 ObjCIvarDecl *Ivar = (*I);
1229 SourceLocation LocStart = Ivar->getLocStart();
1230 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001231 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001232 if (IMD->getIvarRBraceLoc().isValid())
1233 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001234 }
1235 else
1236 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001237
1238 for (ObjCCategoryImplDecl::instmeth_iterator
1239 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1240 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1241 I != E; ++I) {
1242 std::string ResultStr;
1243 ObjCMethodDecl *OMD = *I;
1244 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1245 SourceLocation LocStart = OMD->getLocStart();
1246 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1247
1248 const char *startBuf = SM->getCharacterData(LocStart);
1249 const char *endBuf = SM->getCharacterData(LocEnd);
1250 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1251 }
1252
1253 for (ObjCCategoryImplDecl::classmeth_iterator
1254 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1255 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1256 I != E; ++I) {
1257 std::string ResultStr;
1258 ObjCMethodDecl *OMD = *I;
1259 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1260 SourceLocation LocStart = OMD->getLocStart();
1261 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1262
1263 const char *startBuf = SM->getCharacterData(LocStart);
1264 const char *endBuf = SM->getCharacterData(LocEnd);
1265 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1266 }
1267 for (ObjCCategoryImplDecl::propimpl_iterator
1268 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1269 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1270 I != E; ++I) {
1271 RewritePropertyImplDecl(*I, IMD, CID);
1272 }
1273
1274 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1275}
1276
1277void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001278 // Do not synthesize more than once.
1279 if (ObjCSynthesizedStructs.count(ClassDecl))
1280 return;
1281 // Make sure super class's are written before current class is written.
1282 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1283 while (SuperClass) {
1284 RewriteInterfaceDecl(SuperClass);
1285 SuperClass = SuperClass->getSuperClass();
1286 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001287 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001288 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001289 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001290 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001291 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1292
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001293 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001294 // Mark this typedef as having been written into its c++ equivalent.
1295 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296
1297 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001298 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001299 RewriteProperty(*I);
1300 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001301 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001302 I != E; ++I)
1303 RewriteMethodDeclaration(*I);
1304 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001305 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001306 I != E; ++I)
1307 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001308
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001309 // Lastly, comment out the @end.
1310 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1311 "/* @end */");
1312 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001313}
1314
1315Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1316 SourceRange OldRange = PseudoOp->getSourceRange();
1317
1318 // We just magically know some things about the structure of this
1319 // expression.
1320 ObjCMessageExpr *OldMsg =
1321 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1322 PseudoOp->getNumSemanticExprs() - 1));
1323
1324 // Because the rewriter doesn't allow us to rewrite rewritten code,
1325 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001326 Expr *Base;
1327 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001328 {
1329 DisableReplaceStmtScope S(*this);
1330
1331 // Rebuild the base expression if we have one.
1332 Base = 0;
1333 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1334 Base = OldMsg->getInstanceReceiver();
1335 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1336 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1337 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001338
1339 unsigned numArgs = OldMsg->getNumArgs();
1340 for (unsigned i = 0; i < numArgs; i++) {
1341 Expr *Arg = OldMsg->getArg(i);
1342 if (isa<OpaqueValueExpr>(Arg))
1343 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1344 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1345 Args.push_back(Arg);
1346 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001347 }
1348
1349 // TODO: avoid this copy.
1350 SmallVector<SourceLocation, 1> SelLocs;
1351 OldMsg->getSelectorLocs(SelLocs);
1352
1353 ObjCMessageExpr *NewMsg = 0;
1354 switch (OldMsg->getReceiverKind()) {
1355 case ObjCMessageExpr::Class:
1356 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1357 OldMsg->getValueKind(),
1358 OldMsg->getLeftLoc(),
1359 OldMsg->getClassReceiverTypeInfo(),
1360 OldMsg->getSelector(),
1361 SelLocs,
1362 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001363 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001364 OldMsg->getRightLoc(),
1365 OldMsg->isImplicit());
1366 break;
1367
1368 case ObjCMessageExpr::Instance:
1369 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1370 OldMsg->getValueKind(),
1371 OldMsg->getLeftLoc(),
1372 Base,
1373 OldMsg->getSelector(),
1374 SelLocs,
1375 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001376 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001377 OldMsg->getRightLoc(),
1378 OldMsg->isImplicit());
1379 break;
1380
1381 case ObjCMessageExpr::SuperClass:
1382 case ObjCMessageExpr::SuperInstance:
1383 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1384 OldMsg->getValueKind(),
1385 OldMsg->getLeftLoc(),
1386 OldMsg->getSuperLoc(),
1387 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1388 OldMsg->getSuperType(),
1389 OldMsg->getSelector(),
1390 SelLocs,
1391 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001392 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001393 OldMsg->getRightLoc(),
1394 OldMsg->isImplicit());
1395 break;
1396 }
1397
1398 Stmt *Replacement = SynthMessageExpr(NewMsg);
1399 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1400 return Replacement;
1401}
1402
1403Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1404 SourceRange OldRange = PseudoOp->getSourceRange();
1405
1406 // We just magically know some things about the structure of this
1407 // expression.
1408 ObjCMessageExpr *OldMsg =
1409 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1410
1411 // Because the rewriter doesn't allow us to rewrite rewritten code,
1412 // we need to suppress rewriting the sub-statements.
1413 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001414 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001415 {
1416 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001417 // Rebuild the base expression if we have one.
1418 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1419 Base = OldMsg->getInstanceReceiver();
1420 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1421 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1422 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001423 unsigned numArgs = OldMsg->getNumArgs();
1424 for (unsigned i = 0; i < numArgs; i++) {
1425 Expr *Arg = OldMsg->getArg(i);
1426 if (isa<OpaqueValueExpr>(Arg))
1427 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1428 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1429 Args.push_back(Arg);
1430 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001431 }
1432
1433 // Intentionally empty.
1434 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001435
1436 ObjCMessageExpr *NewMsg = 0;
1437 switch (OldMsg->getReceiverKind()) {
1438 case ObjCMessageExpr::Class:
1439 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1440 OldMsg->getValueKind(),
1441 OldMsg->getLeftLoc(),
1442 OldMsg->getClassReceiverTypeInfo(),
1443 OldMsg->getSelector(),
1444 SelLocs,
1445 OldMsg->getMethodDecl(),
1446 Args,
1447 OldMsg->getRightLoc(),
1448 OldMsg->isImplicit());
1449 break;
1450
1451 case ObjCMessageExpr::Instance:
1452 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1453 OldMsg->getValueKind(),
1454 OldMsg->getLeftLoc(),
1455 Base,
1456 OldMsg->getSelector(),
1457 SelLocs,
1458 OldMsg->getMethodDecl(),
1459 Args,
1460 OldMsg->getRightLoc(),
1461 OldMsg->isImplicit());
1462 break;
1463
1464 case ObjCMessageExpr::SuperClass:
1465 case ObjCMessageExpr::SuperInstance:
1466 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1467 OldMsg->getValueKind(),
1468 OldMsg->getLeftLoc(),
1469 OldMsg->getSuperLoc(),
1470 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1471 OldMsg->getSuperType(),
1472 OldMsg->getSelector(),
1473 SelLocs,
1474 OldMsg->getMethodDecl(),
1475 Args,
1476 OldMsg->getRightLoc(),
1477 OldMsg->isImplicit());
1478 break;
1479 }
1480
1481 Stmt *Replacement = SynthMessageExpr(NewMsg);
1482 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1483 return Replacement;
1484}
1485
1486/// SynthCountByEnumWithState - To print:
1487/// ((unsigned int (*)
1488/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1489/// (void *)objc_msgSend)((id)l_collection,
1490/// sel_registerName(
1491/// "countByEnumeratingWithState:objects:count:"),
1492/// &enumState,
1493/// (id *)__rw_items, (unsigned int)16)
1494///
1495void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1496 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1497 "id *, unsigned int))(void *)objc_msgSend)";
1498 buf += "\n\t\t";
1499 buf += "((id)l_collection,\n\t\t";
1500 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1501 buf += "\n\t\t";
1502 buf += "&enumState, "
1503 "(id *)__rw_items, (unsigned int)16)";
1504}
1505
1506/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1507/// statement to exit to its outer synthesized loop.
1508///
1509Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1510 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1511 return S;
1512 // replace break with goto __break_label
1513 std::string buf;
1514
1515 SourceLocation startLoc = S->getLocStart();
1516 buf = "goto __break_label_";
1517 buf += utostr(ObjCBcLabelNo.back());
1518 ReplaceText(startLoc, strlen("break"), buf);
1519
1520 return 0;
1521}
1522
1523/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1524/// statement to continue with its inner synthesized loop.
1525///
1526Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1527 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1528 return S;
1529 // replace continue with goto __continue_label
1530 std::string buf;
1531
1532 SourceLocation startLoc = S->getLocStart();
1533 buf = "goto __continue_label_";
1534 buf += utostr(ObjCBcLabelNo.back());
1535 ReplaceText(startLoc, strlen("continue"), buf);
1536
1537 return 0;
1538}
1539
1540/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1541/// It rewrites:
1542/// for ( type elem in collection) { stmts; }
1543
1544/// Into:
1545/// {
1546/// type elem;
1547/// struct __objcFastEnumerationState enumState = { 0 };
1548/// id __rw_items[16];
1549/// id l_collection = (id)collection;
1550/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1551/// objects:__rw_items count:16];
1552/// if (limit) {
1553/// unsigned long startMutations = *enumState.mutationsPtr;
1554/// do {
1555/// unsigned long counter = 0;
1556/// do {
1557/// if (startMutations != *enumState.mutationsPtr)
1558/// objc_enumerationMutation(l_collection);
1559/// elem = (type)enumState.itemsPtr[counter++];
1560/// stmts;
1561/// __continue_label: ;
1562/// } while (counter < limit);
1563/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1564/// objects:__rw_items count:16]);
1565/// elem = nil;
1566/// __break_label: ;
1567/// }
1568/// else
1569/// elem = nil;
1570/// }
1571///
1572Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1573 SourceLocation OrigEnd) {
1574 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1575 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1576 "ObjCForCollectionStmt Statement stack mismatch");
1577 assert(!ObjCBcLabelNo.empty() &&
1578 "ObjCForCollectionStmt - Label No stack empty");
1579
1580 SourceLocation startLoc = S->getLocStart();
1581 const char *startBuf = SM->getCharacterData(startLoc);
1582 StringRef elementName;
1583 std::string elementTypeAsString;
1584 std::string buf;
1585 buf = "\n{\n\t";
1586 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1587 // type elem;
1588 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1589 QualType ElementType = cast<ValueDecl>(D)->getType();
1590 if (ElementType->isObjCQualifiedIdType() ||
1591 ElementType->isObjCQualifiedInterfaceType())
1592 // Simply use 'id' for all qualified types.
1593 elementTypeAsString = "id";
1594 else
1595 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1596 buf += elementTypeAsString;
1597 buf += " ";
1598 elementName = D->getName();
1599 buf += elementName;
1600 buf += ";\n\t";
1601 }
1602 else {
1603 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1604 elementName = DR->getDecl()->getName();
1605 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1606 if (VD->getType()->isObjCQualifiedIdType() ||
1607 VD->getType()->isObjCQualifiedInterfaceType())
1608 // Simply use 'id' for all qualified types.
1609 elementTypeAsString = "id";
1610 else
1611 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1612 }
1613
1614 // struct __objcFastEnumerationState enumState = { 0 };
1615 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1616 // id __rw_items[16];
1617 buf += "id __rw_items[16];\n\t";
1618 // id l_collection = (id)
1619 buf += "id l_collection = (id)";
1620 // Find start location of 'collection' the hard way!
1621 const char *startCollectionBuf = startBuf;
1622 startCollectionBuf += 3; // skip 'for'
1623 startCollectionBuf = strchr(startCollectionBuf, '(');
1624 startCollectionBuf++; // skip '('
1625 // find 'in' and skip it.
1626 while (*startCollectionBuf != ' ' ||
1627 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1628 (*(startCollectionBuf+3) != ' ' &&
1629 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1630 startCollectionBuf++;
1631 startCollectionBuf += 3;
1632
1633 // Replace: "for (type element in" with string constructed thus far.
1634 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1635 // Replace ')' in for '(' type elem in collection ')' with ';'
1636 SourceLocation rightParenLoc = S->getRParenLoc();
1637 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1638 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1639 buf = ";\n\t";
1640
1641 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1642 // objects:__rw_items count:16];
1643 // which is synthesized into:
1644 // unsigned int limit =
1645 // ((unsigned int (*)
1646 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1647 // (void *)objc_msgSend)((id)l_collection,
1648 // sel_registerName(
1649 // "countByEnumeratingWithState:objects:count:"),
1650 // (struct __objcFastEnumerationState *)&state,
1651 // (id *)__rw_items, (unsigned int)16);
1652 buf += "unsigned long limit =\n\t\t";
1653 SynthCountByEnumWithState(buf);
1654 buf += ";\n\t";
1655 /// if (limit) {
1656 /// unsigned long startMutations = *enumState.mutationsPtr;
1657 /// do {
1658 /// unsigned long counter = 0;
1659 /// do {
1660 /// if (startMutations != *enumState.mutationsPtr)
1661 /// objc_enumerationMutation(l_collection);
1662 /// elem = (type)enumState.itemsPtr[counter++];
1663 buf += "if (limit) {\n\t";
1664 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1665 buf += "do {\n\t\t";
1666 buf += "unsigned long counter = 0;\n\t\t";
1667 buf += "do {\n\t\t\t";
1668 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1669 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1670 buf += elementName;
1671 buf += " = (";
1672 buf += elementTypeAsString;
1673 buf += ")enumState.itemsPtr[counter++];";
1674 // Replace ')' in for '(' type elem in collection ')' with all of these.
1675 ReplaceText(lparenLoc, 1, buf);
1676
1677 /// __continue_label: ;
1678 /// } while (counter < limit);
1679 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1680 /// objects:__rw_items count:16]);
1681 /// elem = nil;
1682 /// __break_label: ;
1683 /// }
1684 /// else
1685 /// elem = nil;
1686 /// }
1687 ///
1688 buf = ";\n\t";
1689 buf += "__continue_label_";
1690 buf += utostr(ObjCBcLabelNo.back());
1691 buf += ": ;";
1692 buf += "\n\t\t";
1693 buf += "} while (counter < limit);\n\t";
1694 buf += "} while (limit = ";
1695 SynthCountByEnumWithState(buf);
1696 buf += ");\n\t";
1697 buf += elementName;
1698 buf += " = ((";
1699 buf += elementTypeAsString;
1700 buf += ")0);\n\t";
1701 buf += "__break_label_";
1702 buf += utostr(ObjCBcLabelNo.back());
1703 buf += ": ;\n\t";
1704 buf += "}\n\t";
1705 buf += "else\n\t\t";
1706 buf += elementName;
1707 buf += " = ((";
1708 buf += elementTypeAsString;
1709 buf += ")0);\n\t";
1710 buf += "}\n";
1711
1712 // Insert all these *after* the statement body.
1713 // FIXME: If this should support Obj-C++, support CXXTryStmt
1714 if (isa<CompoundStmt>(S->getBody())) {
1715 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1716 InsertText(endBodyLoc, buf);
1717 } else {
1718 /* Need to treat single statements specially. For example:
1719 *
1720 * for (A *a in b) if (stuff()) break;
1721 * for (A *a in b) xxxyy;
1722 *
1723 * The following code simply scans ahead to the semi to find the actual end.
1724 */
1725 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1726 const char *semiBuf = strchr(stmtBuf, ';');
1727 assert(semiBuf && "Can't find ';'");
1728 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1729 InsertText(endBodyLoc, buf);
1730 }
1731 Stmts.pop_back();
1732 ObjCBcLabelNo.pop_back();
1733 return 0;
1734}
1735
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001736static void Write_RethrowObject(std::string &buf) {
1737 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1738 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1739 buf += "\tid rethrow;\n";
1740 buf += "\t} _fin_force_rethow(_rethrow);";
1741}
1742
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001743/// RewriteObjCSynchronizedStmt -
1744/// This routine rewrites @synchronized(expr) stmt;
1745/// into:
1746/// objc_sync_enter(expr);
1747/// @try stmt @finally { objc_sync_exit(expr); }
1748///
1749Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1750 // Get the start location and compute the semi location.
1751 SourceLocation startLoc = S->getLocStart();
1752 const char *startBuf = SM->getCharacterData(startLoc);
1753
1754 assert((*startBuf == '@') && "bogus @synchronized location");
1755
1756 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001757 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001758
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001759 const char *lparenBuf = startBuf;
1760 while (*lparenBuf != '(') lparenBuf++;
1761 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001762
1763 buf = "; objc_sync_enter(_sync_obj);\n";
1764 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1765 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1766 buf += "\n\tid sync_exit;";
1767 buf += "\n\t} _sync_exit(_sync_obj);\n";
1768
1769 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1770 // the sync expression is typically a message expression that's already
1771 // been rewritten! (which implies the SourceLocation's are invalid).
1772 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1773 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1774 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1775 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1776
1777 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1778 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1779 assert (*LBraceLocBuf == '{');
1780 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001781
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001782 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001783 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1784 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001785
1786 buf = "} catch (id e) {_rethrow = e;}\n";
1787 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001788 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001789 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001790
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001791 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001792
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001793 return 0;
1794}
1795
1796void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1797{
1798 // Perform a bottom up traversal of all children.
1799 for (Stmt::child_range CI = S->children(); CI; ++CI)
1800 if (*CI)
1801 WarnAboutReturnGotoStmts(*CI);
1802
1803 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1804 Diags.Report(Context->getFullLoc(S->getLocStart()),
1805 TryFinallyContainsReturnDiag);
1806 }
1807 return;
1808}
1809
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001810Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001811 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001812 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001813 std::string buf;
1814
1815 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001816 if (noCatch)
1817 buf = "{ id volatile _rethrow = 0;\n";
1818 else {
1819 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1820 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001821 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822 // Get the start location and compute the semi location.
1823 SourceLocation startLoc = S->getLocStart();
1824 const char *startBuf = SM->getCharacterData(startLoc);
1825
1826 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001827 if (finalStmt)
1828 ReplaceText(startLoc, 1, buf);
1829 else
1830 // @try -> try
1831 ReplaceText(startLoc, 1, "");
1832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001833 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1834 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001835 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001836
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001837 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001838 bool AtRemoved = false;
1839 if (catchDecl) {
1840 QualType t = catchDecl->getType();
1841 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1842 // Should be a pointer to a class.
1843 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1844 if (IDecl) {
1845 std::string Result;
1846 startBuf = SM->getCharacterData(startLoc);
1847 assert((*startBuf == '@') && "bogus @catch location");
1848 SourceLocation rParenLoc = Catch->getRParenLoc();
1849 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1850
1851 // _objc_exc_Foo *_e as argument to catch.
1852 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1853 Result += " *_"; Result += catchDecl->getNameAsString();
1854 Result += ")";
1855 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1856 // Foo *e = (Foo *)_e;
1857 Result.clear();
1858 Result = "{ ";
1859 Result += IDecl->getNameAsString();
1860 Result += " *"; Result += catchDecl->getNameAsString();
1861 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1862 Result += "_"; Result += catchDecl->getNameAsString();
1863
1864 Result += "; ";
1865 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1866 ReplaceText(lBraceLoc, 1, Result);
1867 AtRemoved = true;
1868 }
1869 }
1870 }
1871 if (!AtRemoved)
1872 // @catch -> catch
1873 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001875 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001876 if (finalStmt) {
1877 buf.clear();
1878 if (noCatch)
1879 buf = "catch (id e) {_rethrow = e;}\n";
1880 else
1881 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1882
1883 SourceLocation startFinalLoc = finalStmt->getLocStart();
1884 ReplaceText(startFinalLoc, 8, buf);
1885 Stmt *body = finalStmt->getFinallyBody();
1886 SourceLocation startFinalBodyLoc = body->getLocStart();
1887 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001888 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001889 ReplaceText(startFinalBodyLoc, 1, buf);
1890
1891 SourceLocation endFinalBodyLoc = body->getLocEnd();
1892 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001893 // Now check for any return/continue/go statements within the @try.
1894 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001895 }
1896
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001897 return 0;
1898}
1899
1900// This can't be done with ReplaceStmt(S, ThrowExpr), since
1901// the throw expression is typically a message expression that's already
1902// been rewritten! (which implies the SourceLocation's are invalid).
1903Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1904 // Get the start location and compute the semi location.
1905 SourceLocation startLoc = S->getLocStart();
1906 const char *startBuf = SM->getCharacterData(startLoc);
1907
1908 assert((*startBuf == '@') && "bogus @throw location");
1909
1910 std::string buf;
1911 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1912 if (S->getThrowExpr())
1913 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001914 else
1915 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001916
1917 // handle "@ throw" correctly.
1918 const char *wBuf = strchr(startBuf, 'w');
1919 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1920 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1921
1922 const char *semiBuf = strchr(startBuf, ';');
1923 assert((*semiBuf == ';') && "@throw: can't find ';'");
1924 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001925 if (S->getThrowExpr())
1926 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001927 return 0;
1928}
1929
1930Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1931 // Create a new string expression.
1932 QualType StrType = Context->getPointerType(Context->CharTy);
1933 std::string StrEncoding;
1934 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1935 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1936 StringLiteral::Ascii, false,
1937 StrType, SourceLocation());
1938 ReplaceStmt(Exp, Replacement);
1939
1940 // Replace this subexpr in the parent.
1941 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1942 return Replacement;
1943}
1944
1945Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1946 if (!SelGetUidFunctionDecl)
1947 SynthSelGetUidFunctionDecl();
1948 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1949 // Create a call to sel_registerName("selName").
1950 SmallVector<Expr*, 8> SelExprs;
1951 QualType argType = Context->getPointerType(Context->CharTy);
1952 SelExprs.push_back(StringLiteral::Create(*Context,
1953 Exp->getSelector().getAsString(),
1954 StringLiteral::Ascii, false,
1955 argType, SourceLocation()));
1956 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1957 &SelExprs[0], SelExprs.size());
1958 ReplaceStmt(Exp, SelExp);
1959 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1960 return SelExp;
1961}
1962
1963CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1964 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1965 SourceLocation EndLoc) {
1966 // Get the type, we will need to reference it in a couple spots.
1967 QualType msgSendType = FD->getType();
1968
1969 // Create a reference to the objc_msgSend() declaration.
1970 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001971 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001972
1973 // Now, we cast the reference to a pointer to the objc_msgSend type.
1974 QualType pToFunc = Context->getPointerType(msgSendType);
1975 ImplicitCastExpr *ICE =
1976 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1977 DRE, 0, VK_RValue);
1978
1979 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1980
1981 CallExpr *Exp =
1982 new (Context) CallExpr(*Context, ICE, args, nargs,
1983 FT->getCallResultType(*Context),
1984 VK_RValue, EndLoc);
1985 return Exp;
1986}
1987
1988static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1989 const char *&startRef, const char *&endRef) {
1990 while (startBuf < endBuf) {
1991 if (*startBuf == '<')
1992 startRef = startBuf; // mark the start.
1993 if (*startBuf == '>') {
1994 if (startRef && *startRef == '<') {
1995 endRef = startBuf; // mark the end.
1996 return true;
1997 }
1998 return false;
1999 }
2000 startBuf++;
2001 }
2002 return false;
2003}
2004
2005static void scanToNextArgument(const char *&argRef) {
2006 int angle = 0;
2007 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2008 if (*argRef == '<')
2009 angle++;
2010 else if (*argRef == '>')
2011 angle--;
2012 argRef++;
2013 }
2014 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2015}
2016
2017bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2018 if (T->isObjCQualifiedIdType())
2019 return true;
2020 if (const PointerType *PT = T->getAs<PointerType>()) {
2021 if (PT->getPointeeType()->isObjCQualifiedIdType())
2022 return true;
2023 }
2024 if (T->isObjCObjectPointerType()) {
2025 T = T->getPointeeType();
2026 return T->isObjCQualifiedInterfaceType();
2027 }
2028 if (T->isArrayType()) {
2029 QualType ElemTy = Context->getBaseElementType(T);
2030 return needToScanForQualifiers(ElemTy);
2031 }
2032 return false;
2033}
2034
2035void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2036 QualType Type = E->getType();
2037 if (needToScanForQualifiers(Type)) {
2038 SourceLocation Loc, EndLoc;
2039
2040 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2041 Loc = ECE->getLParenLoc();
2042 EndLoc = ECE->getRParenLoc();
2043 } else {
2044 Loc = E->getLocStart();
2045 EndLoc = E->getLocEnd();
2046 }
2047 // This will defend against trying to rewrite synthesized expressions.
2048 if (Loc.isInvalid() || EndLoc.isInvalid())
2049 return;
2050
2051 const char *startBuf = SM->getCharacterData(Loc);
2052 const char *endBuf = SM->getCharacterData(EndLoc);
2053 const char *startRef = 0, *endRef = 0;
2054 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2055 // Get the locations of the startRef, endRef.
2056 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2057 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2058 // Comment out the protocol references.
2059 InsertText(LessLoc, "/*");
2060 InsertText(GreaterLoc, "*/");
2061 }
2062 }
2063}
2064
2065void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2066 SourceLocation Loc;
2067 QualType Type;
2068 const FunctionProtoType *proto = 0;
2069 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2070 Loc = VD->getLocation();
2071 Type = VD->getType();
2072 }
2073 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2074 Loc = FD->getLocation();
2075 // Check for ObjC 'id' and class types that have been adorned with protocol
2076 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2077 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2078 assert(funcType && "missing function type");
2079 proto = dyn_cast<FunctionProtoType>(funcType);
2080 if (!proto)
2081 return;
2082 Type = proto->getResultType();
2083 }
2084 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2085 Loc = FD->getLocation();
2086 Type = FD->getType();
2087 }
2088 else
2089 return;
2090
2091 if (needToScanForQualifiers(Type)) {
2092 // Since types are unique, we need to scan the buffer.
2093
2094 const char *endBuf = SM->getCharacterData(Loc);
2095 const char *startBuf = endBuf;
2096 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2097 startBuf--; // scan backward (from the decl location) for return type.
2098 const char *startRef = 0, *endRef = 0;
2099 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2100 // Get the locations of the startRef, endRef.
2101 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2102 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2103 // Comment out the protocol references.
2104 InsertText(LessLoc, "/*");
2105 InsertText(GreaterLoc, "*/");
2106 }
2107 }
2108 if (!proto)
2109 return; // most likely, was a variable
2110 // Now check arguments.
2111 const char *startBuf = SM->getCharacterData(Loc);
2112 const char *startFuncBuf = startBuf;
2113 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2114 if (needToScanForQualifiers(proto->getArgType(i))) {
2115 // Since types are unique, we need to scan the buffer.
2116
2117 const char *endBuf = startBuf;
2118 // scan forward (from the decl location) for argument types.
2119 scanToNextArgument(endBuf);
2120 const char *startRef = 0, *endRef = 0;
2121 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2122 // Get the locations of the startRef, endRef.
2123 SourceLocation LessLoc =
2124 Loc.getLocWithOffset(startRef-startFuncBuf);
2125 SourceLocation GreaterLoc =
2126 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2127 // Comment out the protocol references.
2128 InsertText(LessLoc, "/*");
2129 InsertText(GreaterLoc, "*/");
2130 }
2131 startBuf = ++endBuf;
2132 }
2133 else {
2134 // If the function name is derived from a macro expansion, then the
2135 // argument buffer will not follow the name. Need to speak with Chris.
2136 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2137 startBuf++; // scan forward (from the decl location) for argument types.
2138 startBuf++;
2139 }
2140 }
2141}
2142
2143void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2144 QualType QT = ND->getType();
2145 const Type* TypePtr = QT->getAs<Type>();
2146 if (!isa<TypeOfExprType>(TypePtr))
2147 return;
2148 while (isa<TypeOfExprType>(TypePtr)) {
2149 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2150 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2151 TypePtr = QT->getAs<Type>();
2152 }
2153 // FIXME. This will not work for multiple declarators; as in:
2154 // __typeof__(a) b,c,d;
2155 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2156 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2157 const char *startBuf = SM->getCharacterData(DeclLoc);
2158 if (ND->getInit()) {
2159 std::string Name(ND->getNameAsString());
2160 TypeAsString += " " + Name + " = ";
2161 Expr *E = ND->getInit();
2162 SourceLocation startLoc;
2163 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2164 startLoc = ECE->getLParenLoc();
2165 else
2166 startLoc = E->getLocStart();
2167 startLoc = SM->getExpansionLoc(startLoc);
2168 const char *endBuf = SM->getCharacterData(startLoc);
2169 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2170 }
2171 else {
2172 SourceLocation X = ND->getLocEnd();
2173 X = SM->getExpansionLoc(X);
2174 const char *endBuf = SM->getCharacterData(X);
2175 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2176 }
2177}
2178
2179// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2180void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2181 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2182 SmallVector<QualType, 16> ArgTys;
2183 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2184 QualType getFuncType =
2185 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2186 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2187 SourceLocation(),
2188 SourceLocation(),
2189 SelGetUidIdent, getFuncType, 0,
2190 SC_Extern,
2191 SC_None, false);
2192}
2193
2194void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2195 // declared in <objc/objc.h>
2196 if (FD->getIdentifier() &&
2197 FD->getName() == "sel_registerName") {
2198 SelGetUidFunctionDecl = FD;
2199 return;
2200 }
2201 RewriteObjCQualifiedInterfaceTypes(FD);
2202}
2203
2204void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2205 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2206 const char *argPtr = TypeString.c_str();
2207 if (!strchr(argPtr, '^')) {
2208 Str += TypeString;
2209 return;
2210 }
2211 while (*argPtr) {
2212 Str += (*argPtr == '^' ? '*' : *argPtr);
2213 argPtr++;
2214 }
2215}
2216
2217// FIXME. Consolidate this routine with RewriteBlockPointerType.
2218void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2219 ValueDecl *VD) {
2220 QualType Type = VD->getType();
2221 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2222 const char *argPtr = TypeString.c_str();
2223 int paren = 0;
2224 while (*argPtr) {
2225 switch (*argPtr) {
2226 case '(':
2227 Str += *argPtr;
2228 paren++;
2229 break;
2230 case ')':
2231 Str += *argPtr;
2232 paren--;
2233 break;
2234 case '^':
2235 Str += '*';
2236 if (paren == 1)
2237 Str += VD->getNameAsString();
2238 break;
2239 default:
2240 Str += *argPtr;
2241 break;
2242 }
2243 argPtr++;
2244 }
2245}
2246
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002247void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2248 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2249 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2250 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2251 if (!proto)
2252 return;
2253 QualType Type = proto->getResultType();
2254 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2255 FdStr += " ";
2256 FdStr += FD->getName();
2257 FdStr += "(";
2258 unsigned numArgs = proto->getNumArgs();
2259 for (unsigned i = 0; i < numArgs; i++) {
2260 QualType ArgType = proto->getArgType(i);
2261 RewriteBlockPointerType(FdStr, ArgType);
2262 if (i+1 < numArgs)
2263 FdStr += ", ";
2264 }
2265 FdStr += ");\n";
2266 InsertText(FunLocStart, FdStr);
2267}
2268
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002269// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002270void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2271 if (SuperContructorFunctionDecl)
2272 return;
2273 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2274 SmallVector<QualType, 16> ArgTys;
2275 QualType argT = Context->getObjCIdType();
2276 assert(!argT.isNull() && "Can't find 'id' type");
2277 ArgTys.push_back(argT);
2278 ArgTys.push_back(argT);
2279 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2280 &ArgTys[0], ArgTys.size());
2281 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2282 SourceLocation(),
2283 SourceLocation(),
2284 msgSendIdent, msgSendType, 0,
2285 SC_Extern,
2286 SC_None, false);
2287}
2288
2289// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2290void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2291 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2292 SmallVector<QualType, 16> ArgTys;
2293 QualType argT = Context->getObjCIdType();
2294 assert(!argT.isNull() && "Can't find 'id' type");
2295 ArgTys.push_back(argT);
2296 argT = Context->getObjCSelType();
2297 assert(!argT.isNull() && "Can't find 'SEL' type");
2298 ArgTys.push_back(argT);
2299 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2300 &ArgTys[0], ArgTys.size(),
2301 true /*isVariadic*/);
2302 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2303 SourceLocation(),
2304 SourceLocation(),
2305 msgSendIdent, msgSendType, 0,
2306 SC_Extern,
2307 SC_None, false);
2308}
2309
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002310// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002311void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2312 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002313 SmallVector<QualType, 2> ArgTys;
2314 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002316 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002317 true /*isVariadic*/);
2318 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
2326// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2327void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2328 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2329 SmallVector<QualType, 16> ArgTys;
2330 QualType argT = Context->getObjCIdType();
2331 assert(!argT.isNull() && "Can't find 'id' type");
2332 ArgTys.push_back(argT);
2333 argT = Context->getObjCSelType();
2334 assert(!argT.isNull() && "Can't find 'SEL' type");
2335 ArgTys.push_back(argT);
2336 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2337 &ArgTys[0], ArgTys.size(),
2338 true /*isVariadic*/);
2339 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2340 SourceLocation(),
2341 SourceLocation(),
2342 msgSendIdent, msgSendType, 0,
2343 SC_Extern,
2344 SC_None, false);
2345}
2346
2347// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002348// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002349void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2350 IdentifierInfo *msgSendIdent =
2351 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002352 SmallVector<QualType, 2> ArgTys;
2353 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002354 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002355 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002356 true /*isVariadic*/);
2357 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 msgSendIdent, msgSendType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2366void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2367 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2368 SmallVector<QualType, 16> ArgTys;
2369 QualType argT = Context->getObjCIdType();
2370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
2372 argT = Context->getObjCSelType();
2373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
2375 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2376 &ArgTys[0], ArgTys.size(),
2377 true /*isVariadic*/);
2378 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2379 SourceLocation(),
2380 SourceLocation(),
2381 msgSendIdent, msgSendType, 0,
2382 SC_Extern,
2383 SC_None, false);
2384}
2385
2386// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2387void RewriteModernObjC::SynthGetClassFunctionDecl() {
2388 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2389 SmallVector<QualType, 16> ArgTys;
2390 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2391 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2392 &ArgTys[0], ArgTys.size());
2393 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2394 SourceLocation(),
2395 SourceLocation(),
2396 getClassIdent, getClassType, 0,
2397 SC_Extern,
2398 SC_None, false);
2399}
2400
2401// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2402void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2403 IdentifierInfo *getSuperClassIdent =
2404 &Context->Idents.get("class_getSuperclass");
2405 SmallVector<QualType, 16> ArgTys;
2406 ArgTys.push_back(Context->getObjCClassType());
2407 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2408 &ArgTys[0], ArgTys.size());
2409 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 getSuperClassIdent,
2413 getClassType, 0,
2414 SC_Extern,
2415 SC_None,
2416 false);
2417}
2418
2419// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2420void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2421 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2422 SmallVector<QualType, 16> ArgTys;
2423 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2424 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2425 &ArgTys[0], ArgTys.size());
2426 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2427 SourceLocation(),
2428 SourceLocation(),
2429 getClassIdent, getClassType, 0,
2430 SC_Extern,
2431 SC_None, false);
2432}
2433
2434Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2435 QualType strType = getConstantStringStructType();
2436
2437 std::string S = "__NSConstantStringImpl_";
2438
2439 std::string tmpName = InFileName;
2440 unsigned i;
2441 for (i=0; i < tmpName.length(); i++) {
2442 char c = tmpName.at(i);
2443 // replace any non alphanumeric characters with '_'.
2444 if (!isalpha(c) && (c < '0' || c > '9'))
2445 tmpName[i] = '_';
2446 }
2447 S += tmpName;
2448 S += "_";
2449 S += utostr(NumObjCStringLiterals++);
2450
2451 Preamble += "static __NSConstantStringImpl " + S;
2452 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2453 Preamble += "0x000007c8,"; // utf8_str
2454 // The pretty printer for StringLiteral handles escape characters properly.
2455 std::string prettyBufS;
2456 llvm::raw_string_ostream prettyBuf(prettyBufS);
2457 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2458 PrintingPolicy(LangOpts));
2459 Preamble += prettyBuf.str();
2460 Preamble += ",";
2461 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2462
2463 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2464 SourceLocation(), &Context->Idents.get(S),
2465 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002466 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002467 SourceLocation());
2468 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2469 Context->getPointerType(DRE->getType()),
2470 VK_RValue, OK_Ordinary,
2471 SourceLocation());
2472 // cast to NSConstantString *
2473 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2474 CK_CPointerToObjCPointerCast, Unop);
2475 ReplaceStmt(Exp, cast);
2476 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2477 return cast;
2478}
2479
Fariborz Jahanian55947042012-03-27 20:17:30 +00002480Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2481 unsigned IntSize =
2482 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2483
2484 Expr *FlagExp = IntegerLiteral::Create(*Context,
2485 llvm::APInt(IntSize, Exp->getValue()),
2486 Context->IntTy, Exp->getLocation());
2487 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2488 CK_BitCast, FlagExp);
2489 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2490 cast);
2491 ReplaceStmt(Exp, PE);
2492 return PE;
2493}
2494
Patrick Beardeb382ec2012-04-19 00:25:12 +00002495Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002496 // synthesize declaration of helper functions needed in this routine.
2497 if (!SelGetUidFunctionDecl)
2498 SynthSelGetUidFunctionDecl();
2499 // use objc_msgSend() for all.
2500 if (!MsgSendFunctionDecl)
2501 SynthMsgSendFunctionDecl();
2502 if (!GetClassFunctionDecl)
2503 SynthGetClassFunctionDecl();
2504
2505 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2506 SourceLocation StartLoc = Exp->getLocStart();
2507 SourceLocation EndLoc = Exp->getLocEnd();
2508
2509 // Synthesize a call to objc_msgSend().
2510 SmallVector<Expr*, 4> MsgExprs;
2511 SmallVector<Expr*, 4> ClsExprs;
2512 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002513
Patrick Beardeb382ec2012-04-19 00:25:12 +00002514 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2515 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2516 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002517
Patrick Beardeb382ec2012-04-19 00:25:12 +00002518 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002519 ClsExprs.push_back(StringLiteral::Create(*Context,
2520 clsName->getName(),
2521 StringLiteral::Ascii, false,
2522 argType, SourceLocation()));
2523 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2524 &ClsExprs[0],
2525 ClsExprs.size(),
2526 StartLoc, EndLoc);
2527 MsgExprs.push_back(Cls);
2528
Patrick Beardeb382ec2012-04-19 00:25:12 +00002529 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002530 // it will be the 2nd argument.
2531 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002532 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002533 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002534 StringLiteral::Ascii, false,
2535 argType, SourceLocation()));
2536 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2537 &SelExprs[0], SelExprs.size(),
2538 StartLoc, EndLoc);
2539 MsgExprs.push_back(SelExp);
2540
Patrick Beardeb382ec2012-04-19 00:25:12 +00002541 // User provided sub-expression is the 3rd, and last, argument.
2542 Expr *subExpr = Exp->getSubExpr();
2543 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002544 QualType type = ICE->getType();
2545 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2546 CastKind CK = CK_BitCast;
2547 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2548 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002549 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002550 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002551 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002552
2553 SmallVector<QualType, 4> ArgTypes;
2554 ArgTypes.push_back(Context->getObjCIdType());
2555 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002556 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2557 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002558 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002559
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002560 QualType returnType = Exp->getType();
2561 // Get the type, we will need to reference it in a couple spots.
2562 QualType msgSendType = MsgSendFlavor->getType();
2563
2564 // Create a reference to the objc_msgSend() declaration.
2565 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2566 VK_LValue, SourceLocation());
2567
2568 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002569 Context->getPointerType(Context->VoidTy),
2570 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002571
2572 // Now do the "normal" pointer to function cast.
2573 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002574 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2575 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002576 castType = Context->getPointerType(castType);
2577 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2578 cast);
2579
2580 // Don't forget the parens to enforce the proper binding.
2581 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2582
2583 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2584 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2585 MsgExprs.size(),
2586 FT->getResultType(), VK_RValue,
2587 EndLoc);
2588 ReplaceStmt(Exp, CE);
2589 return CE;
2590}
2591
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002592Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2593 // synthesize declaration of helper functions needed in this routine.
2594 if (!SelGetUidFunctionDecl)
2595 SynthSelGetUidFunctionDecl();
2596 // use objc_msgSend() for all.
2597 if (!MsgSendFunctionDecl)
2598 SynthMsgSendFunctionDecl();
2599 if (!GetClassFunctionDecl)
2600 SynthGetClassFunctionDecl();
2601
2602 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2603 SourceLocation StartLoc = Exp->getLocStart();
2604 SourceLocation EndLoc = Exp->getLocEnd();
2605
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002606 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002607 QualType IntQT = Context->IntTy;
2608 QualType NSArrayFType =
2609 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002610 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002611 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2612 DeclRefExpr *NSArrayDRE =
2613 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2614 SourceLocation());
2615
2616 SmallVector<Expr*, 16> InitExprs;
2617 unsigned NumElements = Exp->getNumElements();
2618 unsigned UnsignedIntSize =
2619 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2620 Expr *count = IntegerLiteral::Create(*Context,
2621 llvm::APInt(UnsignedIntSize, NumElements),
2622 Context->UnsignedIntTy, SourceLocation());
2623 InitExprs.push_back(count);
2624 for (unsigned i = 0; i < NumElements; i++)
2625 InitExprs.push_back(Exp->getElement(i));
2626 Expr *NSArrayCallExpr =
2627 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2628 NSArrayFType, VK_LValue, SourceLocation());
2629
2630 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2631 SourceLocation(),
2632 &Context->Idents.get("arr"),
2633 Context->getPointerType(Context->VoidPtrTy), 0,
2634 /*BitWidth=*/0, /*Mutable=*/true,
2635 /*HasInit=*/false);
2636 MemberExpr *ArrayLiteralME =
2637 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2638 SourceLocation(),
2639 ARRFD->getType(), VK_LValue,
2640 OK_Ordinary);
2641 QualType ConstIdT = Context->getObjCIdType().withConst();
2642 CStyleCastExpr * ArrayLiteralObjects =
2643 NoTypeInfoCStyleCastExpr(Context,
2644 Context->getPointerType(ConstIdT),
2645 CK_BitCast,
2646 ArrayLiteralME);
2647
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002648 // Synthesize a call to objc_msgSend().
2649 SmallVector<Expr*, 32> MsgExprs;
2650 SmallVector<Expr*, 4> ClsExprs;
2651 QualType argType = Context->getPointerType(Context->CharTy);
2652 QualType expType = Exp->getType();
2653
2654 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2655 ObjCInterfaceDecl *Class =
2656 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2657
2658 IdentifierInfo *clsName = Class->getIdentifier();
2659 ClsExprs.push_back(StringLiteral::Create(*Context,
2660 clsName->getName(),
2661 StringLiteral::Ascii, false,
2662 argType, SourceLocation()));
2663 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2664 &ClsExprs[0],
2665 ClsExprs.size(),
2666 StartLoc, EndLoc);
2667 MsgExprs.push_back(Cls);
2668
2669 // Create a call to sel_registerName("arrayWithObjects:count:").
2670 // it will be the 2nd argument.
2671 SmallVector<Expr*, 4> SelExprs;
2672 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2673 SelExprs.push_back(StringLiteral::Create(*Context,
2674 ArrayMethod->getSelector().getAsString(),
2675 StringLiteral::Ascii, false,
2676 argType, SourceLocation()));
2677 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2678 &SelExprs[0], SelExprs.size(),
2679 StartLoc, EndLoc);
2680 MsgExprs.push_back(SelExp);
2681
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002682 // (const id [])objects
2683 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002684
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002685 // (NSUInteger)cnt
2686 Expr *cnt = IntegerLiteral::Create(*Context,
2687 llvm::APInt(UnsignedIntSize, NumElements),
2688 Context->UnsignedIntTy, SourceLocation());
2689 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002690
2691
2692 SmallVector<QualType, 4> ArgTypes;
2693 ArgTypes.push_back(Context->getObjCIdType());
2694 ArgTypes.push_back(Context->getObjCSelType());
2695 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2696 E = ArrayMethod->param_end(); PI != E; ++PI)
2697 ArgTypes.push_back((*PI)->getType());
2698
2699 QualType returnType = Exp->getType();
2700 // Get the type, we will need to reference it in a couple spots.
2701 QualType msgSendType = MsgSendFlavor->getType();
2702
2703 // Create a reference to the objc_msgSend() declaration.
2704 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2705 VK_LValue, SourceLocation());
2706
2707 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2708 Context->getPointerType(Context->VoidTy),
2709 CK_BitCast, DRE);
2710
2711 // Now do the "normal" pointer to function cast.
2712 QualType castType =
2713 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2714 ArrayMethod->isVariadic());
2715 castType = Context->getPointerType(castType);
2716 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2717 cast);
2718
2719 // Don't forget the parens to enforce the proper binding.
2720 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2721
2722 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2723 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2724 MsgExprs.size(),
2725 FT->getResultType(), VK_RValue,
2726 EndLoc);
2727 ReplaceStmt(Exp, CE);
2728 return CE;
2729}
2730
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002731Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2732 // synthesize declaration of helper functions needed in this routine.
2733 if (!SelGetUidFunctionDecl)
2734 SynthSelGetUidFunctionDecl();
2735 // use objc_msgSend() for all.
2736 if (!MsgSendFunctionDecl)
2737 SynthMsgSendFunctionDecl();
2738 if (!GetClassFunctionDecl)
2739 SynthGetClassFunctionDecl();
2740
2741 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2742 SourceLocation StartLoc = Exp->getLocStart();
2743 SourceLocation EndLoc = Exp->getLocEnd();
2744
2745 // Build the expression: __NSContainer_literal(int, ...).arr
2746 QualType IntQT = Context->IntTy;
2747 QualType NSDictFType =
2748 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2749 std::string NSDictFName("__NSContainer_literal");
2750 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2751 DeclRefExpr *NSDictDRE =
2752 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2753 SourceLocation());
2754
2755 SmallVector<Expr*, 16> KeyExprs;
2756 SmallVector<Expr*, 16> ValueExprs;
2757
2758 unsigned NumElements = Exp->getNumElements();
2759 unsigned UnsignedIntSize =
2760 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2761 Expr *count = IntegerLiteral::Create(*Context,
2762 llvm::APInt(UnsignedIntSize, NumElements),
2763 Context->UnsignedIntTy, SourceLocation());
2764 KeyExprs.push_back(count);
2765 ValueExprs.push_back(count);
2766 for (unsigned i = 0; i < NumElements; i++) {
2767 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2768 KeyExprs.push_back(Element.Key);
2769 ValueExprs.push_back(Element.Value);
2770 }
2771
2772 // (const id [])objects
2773 Expr *NSValueCallExpr =
2774 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2775 NSDictFType, VK_LValue, SourceLocation());
2776
2777 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2778 SourceLocation(),
2779 &Context->Idents.get("arr"),
2780 Context->getPointerType(Context->VoidPtrTy), 0,
2781 /*BitWidth=*/0, /*Mutable=*/true,
2782 /*HasInit=*/false);
2783 MemberExpr *DictLiteralValueME =
2784 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2785 SourceLocation(),
2786 ARRFD->getType(), VK_LValue,
2787 OK_Ordinary);
2788 QualType ConstIdT = Context->getObjCIdType().withConst();
2789 CStyleCastExpr * DictValueObjects =
2790 NoTypeInfoCStyleCastExpr(Context,
2791 Context->getPointerType(ConstIdT),
2792 CK_BitCast,
2793 DictLiteralValueME);
2794 // (const id <NSCopying> [])keys
2795 Expr *NSKeyCallExpr =
2796 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2797 NSDictFType, VK_LValue, SourceLocation());
2798
2799 MemberExpr *DictLiteralKeyME =
2800 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2801 SourceLocation(),
2802 ARRFD->getType(), VK_LValue,
2803 OK_Ordinary);
2804
2805 CStyleCastExpr * DictKeyObjects =
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(ConstIdT),
2808 CK_BitCast,
2809 DictLiteralKeyME);
2810
2811
2812
2813 // Synthesize a call to objc_msgSend().
2814 SmallVector<Expr*, 32> MsgExprs;
2815 SmallVector<Expr*, 4> ClsExprs;
2816 QualType argType = Context->getPointerType(Context->CharTy);
2817 QualType expType = Exp->getType();
2818
2819 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2820 ObjCInterfaceDecl *Class =
2821 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2822
2823 IdentifierInfo *clsName = Class->getIdentifier();
2824 ClsExprs.push_back(StringLiteral::Create(*Context,
2825 clsName->getName(),
2826 StringLiteral::Ascii, false,
2827 argType, SourceLocation()));
2828 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2829 &ClsExprs[0],
2830 ClsExprs.size(),
2831 StartLoc, EndLoc);
2832 MsgExprs.push_back(Cls);
2833
2834 // Create a call to sel_registerName("arrayWithObjects:count:").
2835 // it will be the 2nd argument.
2836 SmallVector<Expr*, 4> SelExprs;
2837 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2838 SelExprs.push_back(StringLiteral::Create(*Context,
2839 DictMethod->getSelector().getAsString(),
2840 StringLiteral::Ascii, false,
2841 argType, SourceLocation()));
2842 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2843 &SelExprs[0], SelExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
2847 // (const id [])objects
2848 MsgExprs.push_back(DictValueObjects);
2849
2850 // (const id <NSCopying> [])keys
2851 MsgExprs.push_back(DictKeyObjects);
2852
2853 // (NSUInteger)cnt
2854 Expr *cnt = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 MsgExprs.push_back(cnt);
2858
2859
2860 SmallVector<QualType, 8> ArgTypes;
2861 ArgTypes.push_back(Context->getObjCIdType());
2862 ArgTypes.push_back(Context->getObjCSelType());
2863 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2864 E = DictMethod->param_end(); PI != E; ++PI) {
2865 QualType T = (*PI)->getType();
2866 if (const PointerType* PT = T->getAs<PointerType>()) {
2867 QualType PointeeTy = PT->getPointeeType();
2868 convertToUnqualifiedObjCType(PointeeTy);
2869 T = Context->getPointerType(PointeeTy);
2870 }
2871 ArgTypes.push_back(T);
2872 }
2873
2874 QualType returnType = Exp->getType();
2875 // Get the type, we will need to reference it in a couple spots.
2876 QualType msgSendType = MsgSendFlavor->getType();
2877
2878 // Create a reference to the objc_msgSend() declaration.
2879 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2880 VK_LValue, SourceLocation());
2881
2882 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2883 Context->getPointerType(Context->VoidTy),
2884 CK_BitCast, DRE);
2885
2886 // Now do the "normal" pointer to function cast.
2887 QualType castType =
2888 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2889 DictMethod->isVariadic());
2890 castType = Context->getPointerType(castType);
2891 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2892 cast);
2893
2894 // Don't forget the parens to enforce the proper binding.
2895 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2896
2897 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2898 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2899 MsgExprs.size(),
2900 FT->getResultType(), VK_RValue,
2901 EndLoc);
2902 ReplaceStmt(Exp, CE);
2903 return CE;
2904}
2905
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002906// struct __rw_objc_super {
2907// struct objc_object *object; struct objc_object *superClass;
2908// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002909QualType RewriteModernObjC::getSuperStructType() {
2910 if (!SuperStructDecl) {
2911 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2912 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002913 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002914 QualType FieldTypes[2];
2915
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002916 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002917 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002918 // struct objc_object *superClass;
2919 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002920
2921 // Create fields
2922 for (unsigned i = 0; i < 2; ++i) {
2923 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2924 SourceLocation(),
2925 SourceLocation(), 0,
2926 FieldTypes[i], 0,
2927 /*BitWidth=*/0,
2928 /*Mutable=*/false,
2929 /*HasInit=*/false));
2930 }
2931
2932 SuperStructDecl->completeDefinition();
2933 }
2934 return Context->getTagDeclType(SuperStructDecl);
2935}
2936
2937QualType RewriteModernObjC::getConstantStringStructType() {
2938 if (!ConstantStringDecl) {
2939 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2940 SourceLocation(), SourceLocation(),
2941 &Context->Idents.get("__NSConstantStringImpl"));
2942 QualType FieldTypes[4];
2943
2944 // struct objc_object *receiver;
2945 FieldTypes[0] = Context->getObjCIdType();
2946 // int flags;
2947 FieldTypes[1] = Context->IntTy;
2948 // char *str;
2949 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2950 // long length;
2951 FieldTypes[3] = Context->LongTy;
2952
2953 // Create fields
2954 for (unsigned i = 0; i < 4; ++i) {
2955 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2956 ConstantStringDecl,
2957 SourceLocation(),
2958 SourceLocation(), 0,
2959 FieldTypes[i], 0,
2960 /*BitWidth=*/0,
2961 /*Mutable=*/true,
2962 /*HasInit=*/false));
2963 }
2964
2965 ConstantStringDecl->completeDefinition();
2966 }
2967 return Context->getTagDeclType(ConstantStringDecl);
2968}
2969
2970Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2971 SourceLocation StartLoc,
2972 SourceLocation EndLoc) {
2973 if (!SelGetUidFunctionDecl)
2974 SynthSelGetUidFunctionDecl();
2975 if (!MsgSendFunctionDecl)
2976 SynthMsgSendFunctionDecl();
2977 if (!MsgSendSuperFunctionDecl)
2978 SynthMsgSendSuperFunctionDecl();
2979 if (!MsgSendStretFunctionDecl)
2980 SynthMsgSendStretFunctionDecl();
2981 if (!MsgSendSuperStretFunctionDecl)
2982 SynthMsgSendSuperStretFunctionDecl();
2983 if (!MsgSendFpretFunctionDecl)
2984 SynthMsgSendFpretFunctionDecl();
2985 if (!GetClassFunctionDecl)
2986 SynthGetClassFunctionDecl();
2987 if (!GetSuperClassFunctionDecl)
2988 SynthGetSuperClassFunctionDecl();
2989 if (!GetMetaClassFunctionDecl)
2990 SynthGetMetaClassFunctionDecl();
2991
2992 // default to objc_msgSend().
2993 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2994 // May need to use objc_msgSend_stret() as well.
2995 FunctionDecl *MsgSendStretFlavor = 0;
2996 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2997 QualType resultType = mDecl->getResultType();
2998 if (resultType->isRecordType())
2999 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3000 else if (resultType->isRealFloatingType())
3001 MsgSendFlavor = MsgSendFpretFunctionDecl;
3002 }
3003
3004 // Synthesize a call to objc_msgSend().
3005 SmallVector<Expr*, 8> MsgExprs;
3006 switch (Exp->getReceiverKind()) {
3007 case ObjCMessageExpr::SuperClass: {
3008 MsgSendFlavor = MsgSendSuperFunctionDecl;
3009 if (MsgSendStretFlavor)
3010 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3011 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3012
3013 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3014
3015 SmallVector<Expr*, 4> InitExprs;
3016
3017 // set the receiver to self, the first argument to all methods.
3018 InitExprs.push_back(
3019 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3020 CK_BitCast,
3021 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003022 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003023 Context->getObjCIdType(),
3024 VK_RValue,
3025 SourceLocation()))
3026 ); // set the 'receiver'.
3027
3028 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3029 SmallVector<Expr*, 8> ClsExprs;
3030 QualType argType = Context->getPointerType(Context->CharTy);
3031 ClsExprs.push_back(StringLiteral::Create(*Context,
3032 ClassDecl->getIdentifier()->getName(),
3033 StringLiteral::Ascii, false,
3034 argType, SourceLocation()));
3035 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3036 &ClsExprs[0],
3037 ClsExprs.size(),
3038 StartLoc,
3039 EndLoc);
3040 // (Class)objc_getClass("CurrentClass")
3041 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3042 Context->getObjCClassType(),
3043 CK_BitCast, Cls);
3044 ClsExprs.clear();
3045 ClsExprs.push_back(ArgExpr);
3046 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3047 &ClsExprs[0], ClsExprs.size(),
3048 StartLoc, EndLoc);
3049
3050 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3051 // To turn off a warning, type-cast to 'id'
3052 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3053 NoTypeInfoCStyleCastExpr(Context,
3054 Context->getObjCIdType(),
3055 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003056 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003057 QualType superType = getSuperStructType();
3058 Expr *SuperRep;
3059
3060 if (LangOpts.MicrosoftExt) {
3061 SynthSuperContructorFunctionDecl();
3062 // Simulate a contructor call...
3063 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003064 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003065 SourceLocation());
3066 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3067 InitExprs.size(),
3068 superType, VK_LValue,
3069 SourceLocation());
3070 // The code for super is a little tricky to prevent collision with
3071 // the structure definition in the header. The rewriter has it's own
3072 // internal definition (__rw_objc_super) that is uses. This is why
3073 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003074 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003075 //
3076 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3077 Context->getPointerType(SuperRep->getType()),
3078 VK_RValue, OK_Ordinary,
3079 SourceLocation());
3080 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3081 Context->getPointerType(superType),
3082 CK_BitCast, SuperRep);
3083 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003084 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003085 InitListExpr *ILE =
3086 new (Context) InitListExpr(*Context, SourceLocation(),
3087 &InitExprs[0], InitExprs.size(),
3088 SourceLocation());
3089 TypeSourceInfo *superTInfo
3090 = Context->getTrivialTypeSourceInfo(superType);
3091 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3092 superType, VK_LValue,
3093 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003094 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003095 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3096 Context->getPointerType(SuperRep->getType()),
3097 VK_RValue, OK_Ordinary,
3098 SourceLocation());
3099 }
3100 MsgExprs.push_back(SuperRep);
3101 break;
3102 }
3103
3104 case ObjCMessageExpr::Class: {
3105 SmallVector<Expr*, 8> ClsExprs;
3106 QualType argType = Context->getPointerType(Context->CharTy);
3107 ObjCInterfaceDecl *Class
3108 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3109 IdentifierInfo *clsName = Class->getIdentifier();
3110 ClsExprs.push_back(StringLiteral::Create(*Context,
3111 clsName->getName(),
3112 StringLiteral::Ascii, false,
3113 argType, SourceLocation()));
3114 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3115 &ClsExprs[0],
3116 ClsExprs.size(),
3117 StartLoc, EndLoc);
3118 MsgExprs.push_back(Cls);
3119 break;
3120 }
3121
3122 case ObjCMessageExpr::SuperInstance:{
3123 MsgSendFlavor = MsgSendSuperFunctionDecl;
3124 if (MsgSendStretFlavor)
3125 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3126 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3127 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3128 SmallVector<Expr*, 4> InitExprs;
3129
3130 InitExprs.push_back(
3131 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3132 CK_BitCast,
3133 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003134 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003135 Context->getObjCIdType(),
3136 VK_RValue, SourceLocation()))
3137 ); // set the 'receiver'.
3138
3139 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3140 SmallVector<Expr*, 8> ClsExprs;
3141 QualType argType = Context->getPointerType(Context->CharTy);
3142 ClsExprs.push_back(StringLiteral::Create(*Context,
3143 ClassDecl->getIdentifier()->getName(),
3144 StringLiteral::Ascii, false, argType,
3145 SourceLocation()));
3146 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3147 &ClsExprs[0],
3148 ClsExprs.size(),
3149 StartLoc, EndLoc);
3150 // (Class)objc_getClass("CurrentClass")
3151 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3152 Context->getObjCClassType(),
3153 CK_BitCast, Cls);
3154 ClsExprs.clear();
3155 ClsExprs.push_back(ArgExpr);
3156 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3157 &ClsExprs[0], ClsExprs.size(),
3158 StartLoc, EndLoc);
3159
3160 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3161 // To turn off a warning, type-cast to 'id'
3162 InitExprs.push_back(
3163 // set 'super class', using class_getSuperclass().
3164 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3165 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003166 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003167 QualType superType = getSuperStructType();
3168 Expr *SuperRep;
3169
3170 if (LangOpts.MicrosoftExt) {
3171 SynthSuperContructorFunctionDecl();
3172 // Simulate a contructor call...
3173 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003174 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003175 SourceLocation());
3176 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3177 InitExprs.size(),
3178 superType, VK_LValue, SourceLocation());
3179 // The code for super is a little tricky to prevent collision with
3180 // the structure definition in the header. The rewriter has it's own
3181 // internal definition (__rw_objc_super) that is uses. This is why
3182 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003183 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003184 //
3185 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3186 Context->getPointerType(SuperRep->getType()),
3187 VK_RValue, OK_Ordinary,
3188 SourceLocation());
3189 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3190 Context->getPointerType(superType),
3191 CK_BitCast, SuperRep);
3192 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003193 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003194 InitListExpr *ILE =
3195 new (Context) InitListExpr(*Context, SourceLocation(),
3196 &InitExprs[0], InitExprs.size(),
3197 SourceLocation());
3198 TypeSourceInfo *superTInfo
3199 = Context->getTrivialTypeSourceInfo(superType);
3200 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3201 superType, VK_RValue, ILE,
3202 false);
3203 }
3204 MsgExprs.push_back(SuperRep);
3205 break;
3206 }
3207
3208 case ObjCMessageExpr::Instance: {
3209 // Remove all type-casts because it may contain objc-style types; e.g.
3210 // Foo<Proto> *.
3211 Expr *recExpr = Exp->getInstanceReceiver();
3212 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3213 recExpr = CE->getSubExpr();
3214 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3215 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3216 ? CK_BlockPointerToObjCPointerCast
3217 : CK_CPointerToObjCPointerCast;
3218
3219 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3220 CK, recExpr);
3221 MsgExprs.push_back(recExpr);
3222 break;
3223 }
3224 }
3225
3226 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3227 SmallVector<Expr*, 8> SelExprs;
3228 QualType argType = Context->getPointerType(Context->CharTy);
3229 SelExprs.push_back(StringLiteral::Create(*Context,
3230 Exp->getSelector().getAsString(),
3231 StringLiteral::Ascii, false,
3232 argType, SourceLocation()));
3233 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3234 &SelExprs[0], SelExprs.size(),
3235 StartLoc,
3236 EndLoc);
3237 MsgExprs.push_back(SelExp);
3238
3239 // Now push any user supplied arguments.
3240 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3241 Expr *userExpr = Exp->getArg(i);
3242 // Make all implicit casts explicit...ICE comes in handy:-)
3243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3244 // Reuse the ICE type, it is exactly what the doctor ordered.
3245 QualType type = ICE->getType();
3246 if (needToScanForQualifiers(type))
3247 type = Context->getObjCIdType();
3248 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3249 (void)convertBlockPointerToFunctionPointer(type);
3250 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3251 CastKind CK;
3252 if (SubExpr->getType()->isIntegralType(*Context) &&
3253 type->isBooleanType()) {
3254 CK = CK_IntegralToBoolean;
3255 } else if (type->isObjCObjectPointerType()) {
3256 if (SubExpr->getType()->isBlockPointerType()) {
3257 CK = CK_BlockPointerToObjCPointerCast;
3258 } else if (SubExpr->getType()->isPointerType()) {
3259 CK = CK_CPointerToObjCPointerCast;
3260 } else {
3261 CK = CK_BitCast;
3262 }
3263 } else {
3264 CK = CK_BitCast;
3265 }
3266
3267 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3268 }
3269 // Make id<P...> cast into an 'id' cast.
3270 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3271 if (CE->getType()->isObjCQualifiedIdType()) {
3272 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3273 userExpr = CE->getSubExpr();
3274 CastKind CK;
3275 if (userExpr->getType()->isIntegralType(*Context)) {
3276 CK = CK_IntegralToPointer;
3277 } else if (userExpr->getType()->isBlockPointerType()) {
3278 CK = CK_BlockPointerToObjCPointerCast;
3279 } else if (userExpr->getType()->isPointerType()) {
3280 CK = CK_CPointerToObjCPointerCast;
3281 } else {
3282 CK = CK_BitCast;
3283 }
3284 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3285 CK, userExpr);
3286 }
3287 }
3288 MsgExprs.push_back(userExpr);
3289 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3290 // out the argument in the original expression (since we aren't deleting
3291 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3292 //Exp->setArg(i, 0);
3293 }
3294 // Generate the funky cast.
3295 CastExpr *cast;
3296 SmallVector<QualType, 8> ArgTypes;
3297 QualType returnType;
3298
3299 // Push 'id' and 'SEL', the 2 implicit arguments.
3300 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3301 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3302 else
3303 ArgTypes.push_back(Context->getObjCIdType());
3304 ArgTypes.push_back(Context->getObjCSelType());
3305 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3306 // Push any user argument types.
3307 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3308 E = OMD->param_end(); PI != E; ++PI) {
3309 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3310 ? Context->getObjCIdType()
3311 : (*PI)->getType();
3312 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3313 (void)convertBlockPointerToFunctionPointer(t);
3314 ArgTypes.push_back(t);
3315 }
3316 returnType = Exp->getType();
3317 convertToUnqualifiedObjCType(returnType);
3318 (void)convertBlockPointerToFunctionPointer(returnType);
3319 } else {
3320 returnType = Context->getObjCIdType();
3321 }
3322 // Get the type, we will need to reference it in a couple spots.
3323 QualType msgSendType = MsgSendFlavor->getType();
3324
3325 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003326 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003327 VK_LValue, SourceLocation());
3328
3329 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3330 // If we don't do this cast, we get the following bizarre warning/note:
3331 // xx.m:13: warning: function called through a non-compatible type
3332 // xx.m:13: note: if this code is reached, the program will abort
3333 cast = NoTypeInfoCStyleCastExpr(Context,
3334 Context->getPointerType(Context->VoidTy),
3335 CK_BitCast, DRE);
3336
3337 // Now do the "normal" pointer to function cast.
3338 QualType castType =
3339 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3340 // If we don't have a method decl, force a variadic cast.
3341 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3342 castType = Context->getPointerType(castType);
3343 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3344 cast);
3345
3346 // Don't forget the parens to enforce the proper binding.
3347 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3348
3349 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3350 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3351 MsgExprs.size(),
3352 FT->getResultType(), VK_RValue,
3353 EndLoc);
3354 Stmt *ReplacingStmt = CE;
3355 if (MsgSendStretFlavor) {
3356 // We have the method which returns a struct/union. Must also generate
3357 // call to objc_msgSend_stret and hang both varieties on a conditional
3358 // expression which dictate which one to envoke depending on size of
3359 // method's return type.
3360
3361 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003362 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3363 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003364 VK_LValue, SourceLocation());
3365 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3366 cast = NoTypeInfoCStyleCastExpr(Context,
3367 Context->getPointerType(Context->VoidTy),
3368 CK_BitCast, STDRE);
3369 // Now do the "normal" pointer to function cast.
3370 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3371 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3372 castType = Context->getPointerType(castType);
3373 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3374 cast);
3375
3376 // Don't forget the parens to enforce the proper binding.
3377 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3378
3379 FT = msgSendType->getAs<FunctionType>();
3380 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3381 MsgExprs.size(),
3382 FT->getResultType(), VK_RValue,
3383 SourceLocation());
3384
3385 // Build sizeof(returnType)
3386 UnaryExprOrTypeTraitExpr *sizeofExpr =
3387 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3388 Context->getTrivialTypeSourceInfo(returnType),
3389 Context->getSizeType(), SourceLocation(),
3390 SourceLocation());
3391 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3392 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3393 // For X86 it is more complicated and some kind of target specific routine
3394 // is needed to decide what to do.
3395 unsigned IntSize =
3396 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3397 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3398 llvm::APInt(IntSize, 8),
3399 Context->IntTy,
3400 SourceLocation());
3401 BinaryOperator *lessThanExpr =
3402 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3403 VK_RValue, OK_Ordinary, SourceLocation());
3404 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3405 ConditionalOperator *CondExpr =
3406 new (Context) ConditionalOperator(lessThanExpr,
3407 SourceLocation(), CE,
3408 SourceLocation(), STCE,
3409 returnType, VK_RValue, OK_Ordinary);
3410 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3411 CondExpr);
3412 }
3413 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3414 return ReplacingStmt;
3415}
3416
3417Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3418 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3419 Exp->getLocEnd());
3420
3421 // Now do the actual rewrite.
3422 ReplaceStmt(Exp, ReplacingStmt);
3423
3424 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3425 return ReplacingStmt;
3426}
3427
3428// typedef struct objc_object Protocol;
3429QualType RewriteModernObjC::getProtocolType() {
3430 if (!ProtocolTypeDecl) {
3431 TypeSourceInfo *TInfo
3432 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3433 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3434 SourceLocation(), SourceLocation(),
3435 &Context->Idents.get("Protocol"),
3436 TInfo);
3437 }
3438 return Context->getTypeDeclType(ProtocolTypeDecl);
3439}
3440
3441/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3442/// a synthesized/forward data reference (to the protocol's metadata).
3443/// The forward references (and metadata) are generated in
3444/// RewriteModernObjC::HandleTranslationUnit().
3445Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003446 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3447 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003448 IdentifierInfo *ID = &Context->Idents.get(Name);
3449 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3450 SourceLocation(), ID, getProtocolType(), 0,
3451 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003452 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3453 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003454 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3455 Context->getPointerType(DRE->getType()),
3456 VK_RValue, OK_Ordinary, SourceLocation());
3457 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3458 CK_BitCast,
3459 DerefExpr);
3460 ReplaceStmt(Exp, castExpr);
3461 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3462 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3463 return castExpr;
3464
3465}
3466
3467bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3468 const char *endBuf) {
3469 while (startBuf < endBuf) {
3470 if (*startBuf == '#') {
3471 // Skip whitespace.
3472 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3473 ;
3474 if (!strncmp(startBuf, "if", strlen("if")) ||
3475 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3476 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3477 !strncmp(startBuf, "define", strlen("define")) ||
3478 !strncmp(startBuf, "undef", strlen("undef")) ||
3479 !strncmp(startBuf, "else", strlen("else")) ||
3480 !strncmp(startBuf, "elif", strlen("elif")) ||
3481 !strncmp(startBuf, "endif", strlen("endif")) ||
3482 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3483 !strncmp(startBuf, "include", strlen("include")) ||
3484 !strncmp(startBuf, "import", strlen("import")) ||
3485 !strncmp(startBuf, "include_next", strlen("include_next")))
3486 return true;
3487 }
3488 startBuf++;
3489 }
3490 return false;
3491}
3492
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003493/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003494/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003495bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3496 std::string &Result) {
3497 if (Type->isArrayType()) {
3498 QualType ElemTy = Context->getBaseElementType(Type);
3499 return RewriteObjCFieldDeclType(ElemTy, Result);
3500 }
3501 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003502 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3503 if (RD->isCompleteDefinition()) {
3504 if (RD->isStruct())
3505 Result += "\n\tstruct ";
3506 else if (RD->isUnion())
3507 Result += "\n\tunion ";
3508 else
3509 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003510
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003511 Result += RD->getName();
3512 if (TagsDefinedInIvarDecls.count(RD)) {
3513 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003514 Result += " ";
3515 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003516 }
3517 TagsDefinedInIvarDecls.insert(RD);
3518 Result += " {\n";
3519 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003520 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003521 FieldDecl *FD = *i;
3522 RewriteObjCFieldDecl(FD, Result);
3523 }
3524 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003525 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003526 }
3527 }
3528 else if (Type->isEnumeralType()) {
3529 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3530 if (ED->isCompleteDefinition()) {
3531 Result += "\n\tenum ";
3532 Result += ED->getName();
3533 if (TagsDefinedInIvarDecls.count(ED)) {
3534 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003535 Result += " ";
3536 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003537 }
3538 TagsDefinedInIvarDecls.insert(ED);
3539
3540 Result += " {\n";
3541 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3542 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3543 Result += "\t"; Result += EC->getName(); Result += " = ";
3544 llvm::APSInt Val = EC->getInitVal();
3545 Result += Val.toString(10);
3546 Result += ",\n";
3547 }
3548 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003549 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003550 }
3551 }
3552
3553 Result += "\t";
3554 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003555 return false;
3556}
3557
3558
3559/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3560/// It handles elaborated types, as well as enum types in the process.
3561void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3562 std::string &Result) {
3563 QualType Type = fieldDecl->getType();
3564 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003565
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003566 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3567 if (!EleboratedType)
3568 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003569 Result += Name;
3570 if (fieldDecl->isBitField()) {
3571 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3572 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003573 else if (EleboratedType && Type->isArrayType()) {
3574 CanQualType CType = Context->getCanonicalType(Type);
3575 while (isa<ArrayType>(CType)) {
3576 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3577 Result += "[";
3578 llvm::APInt Dim = CAT->getSize();
3579 Result += utostr(Dim.getZExtValue());
3580 Result += "]";
3581 }
3582 CType = CType->getAs<ArrayType>()->getElementType();
3583 }
3584 }
3585
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003586 Result += ";\n";
3587}
3588
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003589/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3590/// an objective-c class with ivars.
3591void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3592 std::string &Result) {
3593 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3594 assert(CDecl->getName() != "" &&
3595 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003596 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003597 SmallVector<ObjCIvarDecl *, 8> IVars;
3598 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003599 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003600 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003601
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003602 SourceLocation LocStart = CDecl->getLocStart();
3603 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003604
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003605 const char *startBuf = SM->getCharacterData(LocStart);
3606 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003607
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003608 // If no ivars and no root or if its root, directly or indirectly,
3609 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003610 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003611 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3612 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3613 ReplaceText(LocStart, endBuf-startBuf, Result);
3614 return;
3615 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003616
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003617 Result += "\nstruct ";
3618 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003619 Result += "_IMPL {\n";
3620
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003621 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003622 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3623 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3624 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003625 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003626 TagsDefinedInIvarDecls.clear();
3627 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3628 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003629
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003630 Result += "};\n";
3631 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3632 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003633 // Mark this struct as having been generated.
3634 if (!ObjCSynthesizedStructs.insert(CDecl))
3635 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003636}
3637
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003638static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3639 ObjCIvarDecl *IvarDecl, std::string &Result) {
3640 Result += "OBJC_IVAR_$_";
3641 Result += IDecl->getName();
3642 Result += "$";
3643 Result += IvarDecl->getName();
3644}
3645
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003646/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3647/// have been referenced in an ivar access expression.
3648void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3649 std::string &Result) {
3650 // write out ivar offset symbols which have been referenced in an ivar
3651 // access expression.
3652 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3653 if (Ivars.empty())
3654 return;
3655 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3656 e = Ivars.end(); i != e; i++) {
3657 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003658 Result += "\n";
3659 if (LangOpts.MicrosoftExt)
3660 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003661 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003662 if (LangOpts.MicrosoftExt &&
3663 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003664 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3665 Result += "__declspec(dllimport) ";
3666
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003667 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003668 WriteInternalIvarName(CDecl, IvarDecl, Result);
3669 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003670 }
3671}
3672
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003673//===----------------------------------------------------------------------===//
3674// Meta Data Emission
3675//===----------------------------------------------------------------------===//
3676
3677
3678/// RewriteImplementations - This routine rewrites all method implementations
3679/// and emits meta-data.
3680
3681void RewriteModernObjC::RewriteImplementations() {
3682 int ClsDefCount = ClassImplementation.size();
3683 int CatDefCount = CategoryImplementation.size();
3684
3685 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003686 for (int i = 0; i < ClsDefCount; i++) {
3687 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3688 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3689 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003690 assert(false &&
3691 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003692 RewriteImplementationDecl(OIMP);
3693 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003694
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003695 for (int i = 0; i < CatDefCount; i++) {
3696 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3697 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3698 if (CDecl->isImplicitInterfaceDecl())
3699 assert(false &&
3700 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003701 RewriteImplementationDecl(CIMP);
3702 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003703}
3704
3705void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3706 const std::string &Name,
3707 ValueDecl *VD, bool def) {
3708 assert(BlockByRefDeclNo.count(VD) &&
3709 "RewriteByRefString: ByRef decl missing");
3710 if (def)
3711 ResultStr += "struct ";
3712 ResultStr += "__Block_byref_" + Name +
3713 "_" + utostr(BlockByRefDeclNo[VD]) ;
3714}
3715
3716static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3717 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3718 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3719 return false;
3720}
3721
3722std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3723 StringRef funcName,
3724 std::string Tag) {
3725 const FunctionType *AFT = CE->getFunctionType();
3726 QualType RT = AFT->getResultType();
3727 std::string StructRef = "struct " + Tag;
3728 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003729 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003730
3731 BlockDecl *BD = CE->getBlockDecl();
3732
3733 if (isa<FunctionNoProtoType>(AFT)) {
3734 // No user-supplied arguments. Still need to pass in a pointer to the
3735 // block (to reference imported block decl refs).
3736 S += "(" + StructRef + " *__cself)";
3737 } else if (BD->param_empty()) {
3738 S += "(" + StructRef + " *__cself)";
3739 } else {
3740 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3741 assert(FT && "SynthesizeBlockFunc: No function proto");
3742 S += '(';
3743 // first add the implicit argument.
3744 S += StructRef + " *__cself, ";
3745 std::string ParamStr;
3746 for (BlockDecl::param_iterator AI = BD->param_begin(),
3747 E = BD->param_end(); AI != E; ++AI) {
3748 if (AI != BD->param_begin()) S += ", ";
3749 ParamStr = (*AI)->getNameAsString();
3750 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003751 (void)convertBlockPointerToFunctionPointer(QT);
3752 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003753 S += ParamStr;
3754 }
3755 if (FT->isVariadic()) {
3756 if (!BD->param_empty()) S += ", ";
3757 S += "...";
3758 }
3759 S += ')';
3760 }
3761 S += " {\n";
3762
3763 // Create local declarations to avoid rewriting all closure decl ref exprs.
3764 // First, emit a declaration for all "by ref" decls.
3765 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3766 E = BlockByRefDecls.end(); I != E; ++I) {
3767 S += " ";
3768 std::string Name = (*I)->getNameAsString();
3769 std::string TypeString;
3770 RewriteByRefString(TypeString, Name, (*I));
3771 TypeString += " *";
3772 Name = TypeString + Name;
3773 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3774 }
3775 // Next, emit a declaration for all "by copy" declarations.
3776 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3777 E = BlockByCopyDecls.end(); I != E; ++I) {
3778 S += " ";
3779 // Handle nested closure invocation. For example:
3780 //
3781 // void (^myImportedClosure)(void);
3782 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3783 //
3784 // void (^anotherClosure)(void);
3785 // anotherClosure = ^(void) {
3786 // myImportedClosure(); // import and invoke the closure
3787 // };
3788 //
3789 if (isTopLevelBlockPointerType((*I)->getType())) {
3790 RewriteBlockPointerTypeVariable(S, (*I));
3791 S += " = (";
3792 RewriteBlockPointerType(S, (*I)->getType());
3793 S += ")";
3794 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3795 }
3796 else {
3797 std::string Name = (*I)->getNameAsString();
3798 QualType QT = (*I)->getType();
3799 if (HasLocalVariableExternalStorage(*I))
3800 QT = Context->getPointerType(QT);
3801 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3802 S += Name + " = __cself->" +
3803 (*I)->getNameAsString() + "; // bound by copy\n";
3804 }
3805 }
3806 std::string RewrittenStr = RewrittenBlockExprs[CE];
3807 const char *cstr = RewrittenStr.c_str();
3808 while (*cstr++ != '{') ;
3809 S += cstr;
3810 S += "\n";
3811 return S;
3812}
3813
3814std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3815 StringRef funcName,
3816 std::string Tag) {
3817 std::string StructRef = "struct " + Tag;
3818 std::string S = "static void __";
3819
3820 S += funcName;
3821 S += "_block_copy_" + utostr(i);
3822 S += "(" + StructRef;
3823 S += "*dst, " + StructRef;
3824 S += "*src) {";
3825 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3826 E = ImportedBlockDecls.end(); I != E; ++I) {
3827 ValueDecl *VD = (*I);
3828 S += "_Block_object_assign((void*)&dst->";
3829 S += (*I)->getNameAsString();
3830 S += ", (void*)src->";
3831 S += (*I)->getNameAsString();
3832 if (BlockByRefDeclsPtrSet.count((*I)))
3833 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3834 else if (VD->getType()->isBlockPointerType())
3835 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3836 else
3837 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3838 }
3839 S += "}\n";
3840
3841 S += "\nstatic void __";
3842 S += funcName;
3843 S += "_block_dispose_" + utostr(i);
3844 S += "(" + StructRef;
3845 S += "*src) {";
3846 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3847 E = ImportedBlockDecls.end(); I != E; ++I) {
3848 ValueDecl *VD = (*I);
3849 S += "_Block_object_dispose((void*)src->";
3850 S += (*I)->getNameAsString();
3851 if (BlockByRefDeclsPtrSet.count((*I)))
3852 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3853 else if (VD->getType()->isBlockPointerType())
3854 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3855 else
3856 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3857 }
3858 S += "}\n";
3859 return S;
3860}
3861
3862std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3863 std::string Desc) {
3864 std::string S = "\nstruct " + Tag;
3865 std::string Constructor = " " + Tag;
3866
3867 S += " {\n struct __block_impl impl;\n";
3868 S += " struct " + Desc;
3869 S += "* Desc;\n";
3870
3871 Constructor += "(void *fp, "; // Invoke function pointer.
3872 Constructor += "struct " + Desc; // Descriptor pointer.
3873 Constructor += " *desc";
3874
3875 if (BlockDeclRefs.size()) {
3876 // Output all "by copy" declarations.
3877 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3878 E = BlockByCopyDecls.end(); I != E; ++I) {
3879 S += " ";
3880 std::string FieldName = (*I)->getNameAsString();
3881 std::string ArgName = "_" + FieldName;
3882 // Handle nested closure invocation. For example:
3883 //
3884 // void (^myImportedBlock)(void);
3885 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3886 //
3887 // void (^anotherBlock)(void);
3888 // anotherBlock = ^(void) {
3889 // myImportedBlock(); // import and invoke the closure
3890 // };
3891 //
3892 if (isTopLevelBlockPointerType((*I)->getType())) {
3893 S += "struct __block_impl *";
3894 Constructor += ", void *" + ArgName;
3895 } else {
3896 QualType QT = (*I)->getType();
3897 if (HasLocalVariableExternalStorage(*I))
3898 QT = Context->getPointerType(QT);
3899 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3900 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3901 Constructor += ", " + ArgName;
3902 }
3903 S += FieldName + ";\n";
3904 }
3905 // Output all "by ref" declarations.
3906 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3907 E = BlockByRefDecls.end(); I != E; ++I) {
3908 S += " ";
3909 std::string FieldName = (*I)->getNameAsString();
3910 std::string ArgName = "_" + FieldName;
3911 {
3912 std::string TypeString;
3913 RewriteByRefString(TypeString, FieldName, (*I));
3914 TypeString += " *";
3915 FieldName = TypeString + FieldName;
3916 ArgName = TypeString + ArgName;
3917 Constructor += ", " + ArgName;
3918 }
3919 S += FieldName + "; // by ref\n";
3920 }
3921 // Finish writing the constructor.
3922 Constructor += ", int flags=0)";
3923 // Initialize all "by copy" arguments.
3924 bool firsTime = true;
3925 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3926 E = BlockByCopyDecls.end(); I != E; ++I) {
3927 std::string Name = (*I)->getNameAsString();
3928 if (firsTime) {
3929 Constructor += " : ";
3930 firsTime = false;
3931 }
3932 else
3933 Constructor += ", ";
3934 if (isTopLevelBlockPointerType((*I)->getType()))
3935 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3936 else
3937 Constructor += Name + "(_" + Name + ")";
3938 }
3939 // Initialize all "by ref" arguments.
3940 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3941 E = BlockByRefDecls.end(); I != E; ++I) {
3942 std::string Name = (*I)->getNameAsString();
3943 if (firsTime) {
3944 Constructor += " : ";
3945 firsTime = false;
3946 }
3947 else
3948 Constructor += ", ";
3949 Constructor += Name + "(_" + Name + "->__forwarding)";
3950 }
3951
3952 Constructor += " {\n";
3953 if (GlobalVarDecl)
3954 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3955 else
3956 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3957 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3958
3959 Constructor += " Desc = desc;\n";
3960 } else {
3961 // Finish writing the constructor.
3962 Constructor += ", int flags=0) {\n";
3963 if (GlobalVarDecl)
3964 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3965 else
3966 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3967 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3968 Constructor += " Desc = desc;\n";
3969 }
3970 Constructor += " ";
3971 Constructor += "}\n";
3972 S += Constructor;
3973 S += "};\n";
3974 return S;
3975}
3976
3977std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3978 std::string ImplTag, int i,
3979 StringRef FunName,
3980 unsigned hasCopy) {
3981 std::string S = "\nstatic struct " + DescTag;
3982
3983 S += " {\n unsigned long reserved;\n";
3984 S += " unsigned long Block_size;\n";
3985 if (hasCopy) {
3986 S += " void (*copy)(struct ";
3987 S += ImplTag; S += "*, struct ";
3988 S += ImplTag; S += "*);\n";
3989
3990 S += " void (*dispose)(struct ";
3991 S += ImplTag; S += "*);\n";
3992 }
3993 S += "} ";
3994
3995 S += DescTag + "_DATA = { 0, sizeof(struct ";
3996 S += ImplTag + ")";
3997 if (hasCopy) {
3998 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3999 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4000 }
4001 S += "};\n";
4002 return S;
4003}
4004
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004005/// getFunctionSourceLocation - returns start location of a function
4006/// definition. Complication arises when function has declared as
4007/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004008static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4009 FunctionDecl *FD) {
4010 if (!FD->isExternC() || FD->isMain()) {
4011 if (FD->getStorageClassAsWritten() != SC_None)
4012 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004013 return FD->getTypeSpecStartLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004014 }
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004015 const DeclContext *DC = FD->getDeclContext();
4016 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
4017 SourceLocation BodyRBrace = LSD->getRBraceLoc();
4018 // if it is extern "C" {...}, return function decl's own location.
4019 if (BodyRBrace.isValid())
4020 return FD->getTypeSpecStartLoc();
4021 return LSD->getExternLoc();
4022 }
4023 return FD->getTypeSpecStartLoc();
4024}
4025
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004026void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4027 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004028 bool RewriteSC = (GlobalVarDecl &&
4029 !Blocks.empty() &&
4030 GlobalVarDecl->getStorageClass() == SC_Static &&
4031 GlobalVarDecl->getType().getCVRQualifiers());
4032 if (RewriteSC) {
4033 std::string SC(" void __");
4034 SC += GlobalVarDecl->getNameAsString();
4035 SC += "() {}";
4036 InsertText(FunLocStart, SC);
4037 }
4038
4039 // Insert closures that were part of the function.
4040 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4041 CollectBlockDeclRefInfo(Blocks[i]);
4042 // Need to copy-in the inner copied-in variables not actually used in this
4043 // block.
4044 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004045 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004046 ValueDecl *VD = Exp->getDecl();
4047 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004048 if (!VD->hasAttr<BlocksAttr>()) {
4049 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4050 BlockByCopyDeclsPtrSet.insert(VD);
4051 BlockByCopyDecls.push_back(VD);
4052 }
4053 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054 }
John McCallf4b88a42012-03-10 09:33:50 +00004055
4056 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004057 BlockByRefDeclsPtrSet.insert(VD);
4058 BlockByRefDecls.push_back(VD);
4059 }
John McCallf4b88a42012-03-10 09:33:50 +00004060
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004061 // imported objects in the inner blocks not used in the outer
4062 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004063 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004064 VD->getType()->isBlockPointerType())
4065 ImportedBlockDecls.insert(VD);
4066 }
4067
4068 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4069 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4070
4071 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4072
4073 InsertText(FunLocStart, CI);
4074
4075 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4076
4077 InsertText(FunLocStart, CF);
4078
4079 if (ImportedBlockDecls.size()) {
4080 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4081 InsertText(FunLocStart, HF);
4082 }
4083 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4084 ImportedBlockDecls.size() > 0);
4085 InsertText(FunLocStart, BD);
4086
4087 BlockDeclRefs.clear();
4088 BlockByRefDecls.clear();
4089 BlockByRefDeclsPtrSet.clear();
4090 BlockByCopyDecls.clear();
4091 BlockByCopyDeclsPtrSet.clear();
4092 ImportedBlockDecls.clear();
4093 }
4094 if (RewriteSC) {
4095 // Must insert any 'const/volatile/static here. Since it has been
4096 // removed as result of rewriting of block literals.
4097 std::string SC;
4098 if (GlobalVarDecl->getStorageClass() == SC_Static)
4099 SC = "static ";
4100 if (GlobalVarDecl->getType().isConstQualified())
4101 SC += "const ";
4102 if (GlobalVarDecl->getType().isVolatileQualified())
4103 SC += "volatile ";
4104 if (GlobalVarDecl->getType().isRestrictQualified())
4105 SC += "restrict ";
4106 InsertText(FunLocStart, SC);
4107 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004108 if (GlobalConstructionExp) {
4109 // extra fancy dance for global literal expression.
4110
4111 // Always the latest block expression on the block stack.
4112 std::string Tag = "__";
4113 Tag += FunName;
4114 Tag += "_block_impl_";
4115 Tag += utostr(Blocks.size()-1);
4116 std::string globalBuf = "static ";
4117 globalBuf += Tag; globalBuf += " ";
4118 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004119
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004120 llvm::raw_string_ostream constructorExprBuf(SStr);
4121 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4122 PrintingPolicy(LangOpts));
4123 globalBuf += constructorExprBuf.str();
4124 globalBuf += ";\n";
4125 InsertText(FunLocStart, globalBuf);
4126 GlobalConstructionExp = 0;
4127 }
4128
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004129 Blocks.clear();
4130 InnerDeclRefsCount.clear();
4131 InnerDeclRefs.clear();
4132 RewrittenBlockExprs.clear();
4133}
4134
4135void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004136 SourceLocation FunLocStart = getFunctionSourceLocation(*this, FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004137 StringRef FuncName = FD->getName();
4138
4139 SynthesizeBlockLiterals(FunLocStart, FuncName);
4140}
4141
4142static void BuildUniqueMethodName(std::string &Name,
4143 ObjCMethodDecl *MD) {
4144 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4145 Name = IFace->getName();
4146 Name += "__" + MD->getSelector().getAsString();
4147 // Convert colons to underscores.
4148 std::string::size_type loc = 0;
4149 while ((loc = Name.find(":", loc)) != std::string::npos)
4150 Name.replace(loc, 1, "_");
4151}
4152
4153void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4154 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4155 //SourceLocation FunLocStart = MD->getLocStart();
4156 SourceLocation FunLocStart = MD->getLocStart();
4157 std::string FuncName;
4158 BuildUniqueMethodName(FuncName, MD);
4159 SynthesizeBlockLiterals(FunLocStart, FuncName);
4160}
4161
4162void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4163 for (Stmt::child_range CI = S->children(); CI; ++CI)
4164 if (*CI) {
4165 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4166 GetBlockDeclRefExprs(CBE->getBody());
4167 else
4168 GetBlockDeclRefExprs(*CI);
4169 }
4170 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004171 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4172 if (DRE->refersToEnclosingLocal()) {
4173 // FIXME: Handle enums.
4174 if (!isa<FunctionDecl>(DRE->getDecl()))
4175 BlockDeclRefs.push_back(DRE);
4176 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4177 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004178 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004179 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004180
4181 return;
4182}
4183
4184void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004185 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004186 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4187 for (Stmt::child_range CI = S->children(); CI; ++CI)
4188 if (*CI) {
4189 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4190 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4191 GetInnerBlockDeclRefExprs(CBE->getBody(),
4192 InnerBlockDeclRefs,
4193 InnerContexts);
4194 }
4195 else
4196 GetInnerBlockDeclRefExprs(*CI,
4197 InnerBlockDeclRefs,
4198 InnerContexts);
4199
4200 }
4201 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004202 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4203 if (DRE->refersToEnclosingLocal()) {
4204 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4205 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4206 InnerBlockDeclRefs.push_back(DRE);
4207 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4208 if (Var->isFunctionOrMethodVarDecl())
4209 ImportedLocalExternalDecls.insert(Var);
4210 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004211 }
4212
4213 return;
4214}
4215
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004216/// convertObjCTypeToCStyleType - This routine converts such objc types
4217/// as qualified objects, and blocks to their closest c/c++ types that
4218/// it can. It returns true if input type was modified.
4219bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4220 QualType oldT = T;
4221 convertBlockPointerToFunctionPointer(T);
4222 if (T->isFunctionPointerType()) {
4223 QualType PointeeTy;
4224 if (const PointerType* PT = T->getAs<PointerType>()) {
4225 PointeeTy = PT->getPointeeType();
4226 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4227 T = convertFunctionTypeOfBlocks(FT);
4228 T = Context->getPointerType(T);
4229 }
4230 }
4231 }
4232
4233 convertToUnqualifiedObjCType(T);
4234 return T != oldT;
4235}
4236
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004237/// convertFunctionTypeOfBlocks - This routine converts a function type
4238/// whose result type may be a block pointer or whose argument type(s)
4239/// might be block pointers to an equivalent function type replacing
4240/// all block pointers to function pointers.
4241QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4242 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4243 // FTP will be null for closures that don't take arguments.
4244 // Generate a funky cast.
4245 SmallVector<QualType, 8> ArgTypes;
4246 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004247 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004248
4249 if (FTP) {
4250 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4251 E = FTP->arg_type_end(); I && (I != E); ++I) {
4252 QualType t = *I;
4253 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004254 if (convertObjCTypeToCStyleType(t))
4255 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004256 ArgTypes.push_back(t);
4257 }
4258 }
4259 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004260 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004261 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4262 else FuncType = QualType(FT, 0);
4263 return FuncType;
4264}
4265
4266Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4267 // Navigate to relevant type information.
4268 const BlockPointerType *CPT = 0;
4269
4270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4271 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004272 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4273 CPT = MExpr->getType()->getAs<BlockPointerType>();
4274 }
4275 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4276 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4277 }
4278 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4279 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4280 else if (const ConditionalOperator *CEXPR =
4281 dyn_cast<ConditionalOperator>(BlockExp)) {
4282 Expr *LHSExp = CEXPR->getLHS();
4283 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4284 Expr *RHSExp = CEXPR->getRHS();
4285 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4286 Expr *CONDExp = CEXPR->getCond();
4287 ConditionalOperator *CondExpr =
4288 new (Context) ConditionalOperator(CONDExp,
4289 SourceLocation(), cast<Expr>(LHSStmt),
4290 SourceLocation(), cast<Expr>(RHSStmt),
4291 Exp->getType(), VK_RValue, OK_Ordinary);
4292 return CondExpr;
4293 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4294 CPT = IRE->getType()->getAs<BlockPointerType>();
4295 } else if (const PseudoObjectExpr *POE
4296 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4297 CPT = POE->getType()->castAs<BlockPointerType>();
4298 } else {
4299 assert(1 && "RewriteBlockClass: Bad type");
4300 }
4301 assert(CPT && "RewriteBlockClass: Bad type");
4302 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4303 assert(FT && "RewriteBlockClass: Bad type");
4304 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4305 // FTP will be null for closures that don't take arguments.
4306
4307 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4308 SourceLocation(), SourceLocation(),
4309 &Context->Idents.get("__block_impl"));
4310 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4311
4312 // Generate a funky cast.
4313 SmallVector<QualType, 8> ArgTypes;
4314
4315 // Push the block argument type.
4316 ArgTypes.push_back(PtrBlock);
4317 if (FTP) {
4318 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4319 E = FTP->arg_type_end(); I && (I != E); ++I) {
4320 QualType t = *I;
4321 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4322 if (!convertBlockPointerToFunctionPointer(t))
4323 convertToUnqualifiedObjCType(t);
4324 ArgTypes.push_back(t);
4325 }
4326 }
4327 // Now do the pointer to function cast.
4328 QualType PtrToFuncCastType
4329 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4330
4331 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4332
4333 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4334 CK_BitCast,
4335 const_cast<Expr*>(BlockExp));
4336 // Don't forget the parens to enforce the proper binding.
4337 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4338 BlkCast);
4339 //PE->dump();
4340
4341 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4342 SourceLocation(),
4343 &Context->Idents.get("FuncPtr"),
4344 Context->VoidPtrTy, 0,
4345 /*BitWidth=*/0, /*Mutable=*/true,
4346 /*HasInit=*/false);
4347 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4348 FD->getType(), VK_LValue,
4349 OK_Ordinary);
4350
4351
4352 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4353 CK_BitCast, ME);
4354 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4355
4356 SmallVector<Expr*, 8> BlkExprs;
4357 // Add the implicit argument.
4358 BlkExprs.push_back(BlkCast);
4359 // Add the user arguments.
4360 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4361 E = Exp->arg_end(); I != E; ++I) {
4362 BlkExprs.push_back(*I);
4363 }
4364 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4365 BlkExprs.size(),
4366 Exp->getType(), VK_RValue,
4367 SourceLocation());
4368 return CE;
4369}
4370
4371// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004372// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004373// For example:
4374//
4375// int main() {
4376// __block Foo *f;
4377// __block int i;
4378//
4379// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004380// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004381// i = 77;
4382// };
4383//}
John McCallf4b88a42012-03-10 09:33:50 +00004384Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004385 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4386 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004387 ValueDecl *VD = DeclRefExp->getDecl();
4388 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004389
4390 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4391 SourceLocation(),
4392 &Context->Idents.get("__forwarding"),
4393 Context->VoidPtrTy, 0,
4394 /*BitWidth=*/0, /*Mutable=*/true,
4395 /*HasInit=*/false);
4396 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4397 FD, SourceLocation(),
4398 FD->getType(), VK_LValue,
4399 OK_Ordinary);
4400
4401 StringRef Name = VD->getName();
4402 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4403 &Context->Idents.get(Name),
4404 Context->VoidPtrTy, 0,
4405 /*BitWidth=*/0, /*Mutable=*/true,
4406 /*HasInit=*/false);
4407 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4408 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4409
4410
4411
4412 // Need parens to enforce precedence.
4413 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4414 DeclRefExp->getExprLoc(),
4415 ME);
4416 ReplaceStmt(DeclRefExp, PE);
4417 return PE;
4418}
4419
4420// Rewrites the imported local variable V with external storage
4421// (static, extern, etc.) as *V
4422//
4423Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4424 ValueDecl *VD = DRE->getDecl();
4425 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4426 if (!ImportedLocalExternalDecls.count(Var))
4427 return DRE;
4428 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4429 VK_LValue, OK_Ordinary,
4430 DRE->getLocation());
4431 // Need parens to enforce precedence.
4432 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4433 Exp);
4434 ReplaceStmt(DRE, PE);
4435 return PE;
4436}
4437
4438void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4439 SourceLocation LocStart = CE->getLParenLoc();
4440 SourceLocation LocEnd = CE->getRParenLoc();
4441
4442 // Need to avoid trying to rewrite synthesized casts.
4443 if (LocStart.isInvalid())
4444 return;
4445 // Need to avoid trying to rewrite casts contained in macros.
4446 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4447 return;
4448
4449 const char *startBuf = SM->getCharacterData(LocStart);
4450 const char *endBuf = SM->getCharacterData(LocEnd);
4451 QualType QT = CE->getType();
4452 const Type* TypePtr = QT->getAs<Type>();
4453 if (isa<TypeOfExprType>(TypePtr)) {
4454 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4455 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4456 std::string TypeAsString = "(";
4457 RewriteBlockPointerType(TypeAsString, QT);
4458 TypeAsString += ")";
4459 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4460 return;
4461 }
4462 // advance the location to startArgList.
4463 const char *argPtr = startBuf;
4464
4465 while (*argPtr++ && (argPtr < endBuf)) {
4466 switch (*argPtr) {
4467 case '^':
4468 // Replace the '^' with '*'.
4469 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4470 ReplaceText(LocStart, 1, "*");
4471 break;
4472 }
4473 }
4474 return;
4475}
4476
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004477void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4478 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004479 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4480 CastKind != CK_AnyPointerToBlockPointerCast)
4481 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004482
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004483 QualType QT = IC->getType();
4484 (void)convertBlockPointerToFunctionPointer(QT);
4485 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4486 std::string Str = "(";
4487 Str += TypeString;
4488 Str += ")";
4489 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4490
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004491 return;
4492}
4493
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004494void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4495 SourceLocation DeclLoc = FD->getLocation();
4496 unsigned parenCount = 0;
4497
4498 // We have 1 or more arguments that have closure pointers.
4499 const char *startBuf = SM->getCharacterData(DeclLoc);
4500 const char *startArgList = strchr(startBuf, '(');
4501
4502 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4503
4504 parenCount++;
4505 // advance the location to startArgList.
4506 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4507 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4508
4509 const char *argPtr = startArgList;
4510
4511 while (*argPtr++ && parenCount) {
4512 switch (*argPtr) {
4513 case '^':
4514 // Replace the '^' with '*'.
4515 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4516 ReplaceText(DeclLoc, 1, "*");
4517 break;
4518 case '(':
4519 parenCount++;
4520 break;
4521 case ')':
4522 parenCount--;
4523 break;
4524 }
4525 }
4526 return;
4527}
4528
4529bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4530 const FunctionProtoType *FTP;
4531 const PointerType *PT = QT->getAs<PointerType>();
4532 if (PT) {
4533 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4534 } else {
4535 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4536 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4537 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4538 }
4539 if (FTP) {
4540 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4541 E = FTP->arg_type_end(); I != E; ++I)
4542 if (isTopLevelBlockPointerType(*I))
4543 return true;
4544 }
4545 return false;
4546}
4547
4548bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4549 const FunctionProtoType *FTP;
4550 const PointerType *PT = QT->getAs<PointerType>();
4551 if (PT) {
4552 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4553 } else {
4554 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4555 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4556 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4557 }
4558 if (FTP) {
4559 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4560 E = FTP->arg_type_end(); I != E; ++I) {
4561 if ((*I)->isObjCQualifiedIdType())
4562 return true;
4563 if ((*I)->isObjCObjectPointerType() &&
4564 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4565 return true;
4566 }
4567
4568 }
4569 return false;
4570}
4571
4572void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4573 const char *&RParen) {
4574 const char *argPtr = strchr(Name, '(');
4575 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4576
4577 LParen = argPtr; // output the start.
4578 argPtr++; // skip past the left paren.
4579 unsigned parenCount = 1;
4580
4581 while (*argPtr && parenCount) {
4582 switch (*argPtr) {
4583 case '(': parenCount++; break;
4584 case ')': parenCount--; break;
4585 default: break;
4586 }
4587 if (parenCount) argPtr++;
4588 }
4589 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4590 RParen = argPtr; // output the end
4591}
4592
4593void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4594 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4595 RewriteBlockPointerFunctionArgs(FD);
4596 return;
4597 }
4598 // Handle Variables and Typedefs.
4599 SourceLocation DeclLoc = ND->getLocation();
4600 QualType DeclT;
4601 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4602 DeclT = VD->getType();
4603 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4604 DeclT = TDD->getUnderlyingType();
4605 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4606 DeclT = FD->getType();
4607 else
4608 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4609
4610 const char *startBuf = SM->getCharacterData(DeclLoc);
4611 const char *endBuf = startBuf;
4612 // scan backward (from the decl location) for the end of the previous decl.
4613 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4614 startBuf--;
4615 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4616 std::string buf;
4617 unsigned OrigLength=0;
4618 // *startBuf != '^' if we are dealing with a pointer to function that
4619 // may take block argument types (which will be handled below).
4620 if (*startBuf == '^') {
4621 // Replace the '^' with '*', computing a negative offset.
4622 buf = '*';
4623 startBuf++;
4624 OrigLength++;
4625 }
4626 while (*startBuf != ')') {
4627 buf += *startBuf;
4628 startBuf++;
4629 OrigLength++;
4630 }
4631 buf += ')';
4632 OrigLength++;
4633
4634 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4635 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4636 // Replace the '^' with '*' for arguments.
4637 // Replace id<P> with id/*<>*/
4638 DeclLoc = ND->getLocation();
4639 startBuf = SM->getCharacterData(DeclLoc);
4640 const char *argListBegin, *argListEnd;
4641 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4642 while (argListBegin < argListEnd) {
4643 if (*argListBegin == '^')
4644 buf += '*';
4645 else if (*argListBegin == '<') {
4646 buf += "/*";
4647 buf += *argListBegin++;
4648 OrigLength++;;
4649 while (*argListBegin != '>') {
4650 buf += *argListBegin++;
4651 OrigLength++;
4652 }
4653 buf += *argListBegin;
4654 buf += "*/";
4655 }
4656 else
4657 buf += *argListBegin;
4658 argListBegin++;
4659 OrigLength++;
4660 }
4661 buf += ')';
4662 OrigLength++;
4663 }
4664 ReplaceText(Start, OrigLength, buf);
4665
4666 return;
4667}
4668
4669
4670/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4671/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4672/// struct Block_byref_id_object *src) {
4673/// _Block_object_assign (&_dest->object, _src->object,
4674/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4675/// [|BLOCK_FIELD_IS_WEAK]) // object
4676/// _Block_object_assign(&_dest->object, _src->object,
4677/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4678/// [|BLOCK_FIELD_IS_WEAK]) // block
4679/// }
4680/// And:
4681/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4682/// _Block_object_dispose(_src->object,
4683/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4684/// [|BLOCK_FIELD_IS_WEAK]) // object
4685/// _Block_object_dispose(_src->object,
4686/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4687/// [|BLOCK_FIELD_IS_WEAK]) // block
4688/// }
4689
4690std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4691 int flag) {
4692 std::string S;
4693 if (CopyDestroyCache.count(flag))
4694 return S;
4695 CopyDestroyCache.insert(flag);
4696 S = "static void __Block_byref_id_object_copy_";
4697 S += utostr(flag);
4698 S += "(void *dst, void *src) {\n";
4699
4700 // offset into the object pointer is computed as:
4701 // void * + void* + int + int + void* + void *
4702 unsigned IntSize =
4703 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4704 unsigned VoidPtrSize =
4705 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4706
4707 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4708 S += " _Block_object_assign((char*)dst + ";
4709 S += utostr(offset);
4710 S += ", *(void * *) ((char*)src + ";
4711 S += utostr(offset);
4712 S += "), ";
4713 S += utostr(flag);
4714 S += ");\n}\n";
4715
4716 S += "static void __Block_byref_id_object_dispose_";
4717 S += utostr(flag);
4718 S += "(void *src) {\n";
4719 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4720 S += utostr(offset);
4721 S += "), ";
4722 S += utostr(flag);
4723 S += ");\n}\n";
4724 return S;
4725}
4726
4727/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4728/// the declaration into:
4729/// struct __Block_byref_ND {
4730/// void *__isa; // NULL for everything except __weak pointers
4731/// struct __Block_byref_ND *__forwarding;
4732/// int32_t __flags;
4733/// int32_t __size;
4734/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4735/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4736/// typex ND;
4737/// };
4738///
4739/// It then replaces declaration of ND variable with:
4740/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4741/// __size=sizeof(struct __Block_byref_ND),
4742/// ND=initializer-if-any};
4743///
4744///
4745void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004746 int flag = 0;
4747 int isa = 0;
4748 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4749 if (DeclLoc.isInvalid())
4750 // If type location is missing, it is because of missing type (a warning).
4751 // Use variable's location which is good for this case.
4752 DeclLoc = ND->getLocation();
4753 const char *startBuf = SM->getCharacterData(DeclLoc);
4754 SourceLocation X = ND->getLocEnd();
4755 X = SM->getExpansionLoc(X);
4756 const char *endBuf = SM->getCharacterData(X);
4757 std::string Name(ND->getNameAsString());
4758 std::string ByrefType;
4759 RewriteByRefString(ByrefType, Name, ND, true);
4760 ByrefType += " {\n";
4761 ByrefType += " void *__isa;\n";
4762 RewriteByRefString(ByrefType, Name, ND);
4763 ByrefType += " *__forwarding;\n";
4764 ByrefType += " int __flags;\n";
4765 ByrefType += " int __size;\n";
4766 // Add void *__Block_byref_id_object_copy;
4767 // void *__Block_byref_id_object_dispose; if needed.
4768 QualType Ty = ND->getType();
4769 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4770 if (HasCopyAndDispose) {
4771 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4772 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4773 }
4774
4775 QualType T = Ty;
4776 (void)convertBlockPointerToFunctionPointer(T);
4777 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4778
4779 ByrefType += " " + Name + ";\n";
4780 ByrefType += "};\n";
4781 // Insert this type in global scope. It is needed by helper function.
4782 SourceLocation FunLocStart;
4783 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004784 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004785 else {
4786 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4787 FunLocStart = CurMethodDef->getLocStart();
4788 }
4789 InsertText(FunLocStart, ByrefType);
4790 if (Ty.isObjCGCWeak()) {
4791 flag |= BLOCK_FIELD_IS_WEAK;
4792 isa = 1;
4793 }
4794
4795 if (HasCopyAndDispose) {
4796 flag = BLOCK_BYREF_CALLER;
4797 QualType Ty = ND->getType();
4798 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4799 if (Ty->isBlockPointerType())
4800 flag |= BLOCK_FIELD_IS_BLOCK;
4801 else
4802 flag |= BLOCK_FIELD_IS_OBJECT;
4803 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4804 if (!HF.empty())
4805 InsertText(FunLocStart, HF);
4806 }
4807
4808 // struct __Block_byref_ND ND =
4809 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4810 // initializer-if-any};
4811 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004812 // FIXME. rewriter does not support __block c++ objects which
4813 // require construction.
4814 if (hasInit && dyn_cast<CXXConstructExpr>(ND->getInit()))
4815 hasInit = false;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004816 unsigned flags = 0;
4817 if (HasCopyAndDispose)
4818 flags |= BLOCK_HAS_COPY_DISPOSE;
4819 Name = ND->getNameAsString();
4820 ByrefType.clear();
4821 RewriteByRefString(ByrefType, Name, ND);
4822 std::string ForwardingCastType("(");
4823 ForwardingCastType += ByrefType + " *)";
4824 if (!hasInit) {
4825 ByrefType += " " + Name + " = {(void*)";
4826 ByrefType += utostr(isa);
4827 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4828 ByrefType += utostr(flags);
4829 ByrefType += ", ";
4830 ByrefType += "sizeof(";
4831 RewriteByRefString(ByrefType, Name, ND);
4832 ByrefType += ")";
4833 if (HasCopyAndDispose) {
4834 ByrefType += ", __Block_byref_id_object_copy_";
4835 ByrefType += utostr(flag);
4836 ByrefType += ", __Block_byref_id_object_dispose_";
4837 ByrefType += utostr(flag);
4838 }
4839 ByrefType += "};\n";
4840 unsigned nameSize = Name.size();
4841 // for block or function pointer declaration. Name is aleady
4842 // part of the declaration.
4843 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4844 nameSize = 1;
4845 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4846 }
4847 else {
4848 SourceLocation startLoc;
4849 Expr *E = ND->getInit();
4850 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4851 startLoc = ECE->getLParenLoc();
4852 else
4853 startLoc = E->getLocStart();
4854 startLoc = SM->getExpansionLoc(startLoc);
4855 endBuf = SM->getCharacterData(startLoc);
4856 ByrefType += " " + Name;
4857 ByrefType += " = {(void*)";
4858 ByrefType += utostr(isa);
4859 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4860 ByrefType += utostr(flags);
4861 ByrefType += ", ";
4862 ByrefType += "sizeof(";
4863 RewriteByRefString(ByrefType, Name, ND);
4864 ByrefType += "), ";
4865 if (HasCopyAndDispose) {
4866 ByrefType += "__Block_byref_id_object_copy_";
4867 ByrefType += utostr(flag);
4868 ByrefType += ", __Block_byref_id_object_dispose_";
4869 ByrefType += utostr(flag);
4870 ByrefType += ", ";
4871 }
4872 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4873
4874 // Complete the newly synthesized compound expression by inserting a right
4875 // curly brace before the end of the declaration.
4876 // FIXME: This approach avoids rewriting the initializer expression. It
4877 // also assumes there is only one declarator. For example, the following
4878 // isn't currently supported by this routine (in general):
4879 //
4880 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4881 //
4882 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4883 const char *semiBuf = strchr(startInitializerBuf, ';');
4884 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4885 SourceLocation semiLoc =
4886 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4887
4888 InsertText(semiLoc, "}");
4889 }
4890 return;
4891}
4892
4893void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4894 // Add initializers for any closure decl refs.
4895 GetBlockDeclRefExprs(Exp->getBody());
4896 if (BlockDeclRefs.size()) {
4897 // Unique all "by copy" declarations.
4898 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004899 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004900 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4901 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4902 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4903 }
4904 }
4905 // Unique all "by ref" declarations.
4906 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004907 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004908 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4909 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4910 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4911 }
4912 }
4913 // Find any imported blocks...they will need special attention.
4914 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004915 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004916 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4917 BlockDeclRefs[i]->getType()->isBlockPointerType())
4918 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4919 }
4920}
4921
4922FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4923 IdentifierInfo *ID = &Context->Idents.get(name);
4924 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4925 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4926 SourceLocation(), ID, FType, 0, SC_Extern,
4927 SC_None, false, false);
4928}
4929
4930Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004931 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004932
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004933 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004934
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004935 Blocks.push_back(Exp);
4936
4937 CollectBlockDeclRefInfo(Exp);
4938
4939 // Add inner imported variables now used in current block.
4940 int countOfInnerDecls = 0;
4941 if (!InnerBlockDeclRefs.empty()) {
4942 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004943 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004944 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004945 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004946 // We need to save the copied-in variables in nested
4947 // blocks because it is needed at the end for some of the API generations.
4948 // See SynthesizeBlockLiterals routine.
4949 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4950 BlockDeclRefs.push_back(Exp);
4951 BlockByCopyDeclsPtrSet.insert(VD);
4952 BlockByCopyDecls.push_back(VD);
4953 }
John McCallf4b88a42012-03-10 09:33:50 +00004954 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004955 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4956 BlockDeclRefs.push_back(Exp);
4957 BlockByRefDeclsPtrSet.insert(VD);
4958 BlockByRefDecls.push_back(VD);
4959 }
4960 }
4961 // Find any imported blocks...they will need special attention.
4962 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004963 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004964 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4965 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4966 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4967 }
4968 InnerDeclRefsCount.push_back(countOfInnerDecls);
4969
4970 std::string FuncName;
4971
4972 if (CurFunctionDef)
4973 FuncName = CurFunctionDef->getNameAsString();
4974 else if (CurMethodDef)
4975 BuildUniqueMethodName(FuncName, CurMethodDef);
4976 else if (GlobalVarDecl)
4977 FuncName = std::string(GlobalVarDecl->getNameAsString());
4978
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004979 bool GlobalBlockExpr =
4980 block->getDeclContext()->getRedeclContext()->isFileContext();
4981
4982 if (GlobalBlockExpr && !GlobalVarDecl) {
4983 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4984 GlobalBlockExpr = false;
4985 }
4986
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004987 std::string BlockNumber = utostr(Blocks.size()-1);
4988
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004989 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4990
4991 // Get a pointer to the function type so we can cast appropriately.
4992 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4993 QualType FType = Context->getPointerType(BFT);
4994
4995 FunctionDecl *FD;
4996 Expr *NewRep;
4997
4998 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004999 std::string Tag;
5000
5001 if (GlobalBlockExpr)
5002 Tag = "__global_";
5003 else
5004 Tag = "__";
5005 Tag += FuncName + "_block_impl_" + BlockNumber;
5006
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005007 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005008 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005009 SourceLocation());
5010
5011 SmallVector<Expr*, 4> InitExprs;
5012
5013 // Initialize the block function.
5014 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005015 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5016 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005017 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5018 CK_BitCast, Arg);
5019 InitExprs.push_back(castExpr);
5020
5021 // Initialize the block descriptor.
5022 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5023
5024 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5025 SourceLocation(), SourceLocation(),
5026 &Context->Idents.get(DescData.c_str()),
5027 Context->VoidPtrTy, 0,
5028 SC_Static, SC_None);
5029 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005030 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005031 Context->VoidPtrTy,
5032 VK_LValue,
5033 SourceLocation()),
5034 UO_AddrOf,
5035 Context->getPointerType(Context->VoidPtrTy),
5036 VK_RValue, OK_Ordinary,
5037 SourceLocation());
5038 InitExprs.push_back(DescRefExpr);
5039
5040 // Add initializers for any closure decl refs.
5041 if (BlockDeclRefs.size()) {
5042 Expr *Exp;
5043 // Output all "by copy" declarations.
5044 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5045 E = BlockByCopyDecls.end(); I != E; ++I) {
5046 if (isObjCType((*I)->getType())) {
5047 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5048 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005049 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5050 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005051 if (HasLocalVariableExternalStorage(*I)) {
5052 QualType QT = (*I)->getType();
5053 QT = Context->getPointerType(QT);
5054 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5055 OK_Ordinary, SourceLocation());
5056 }
5057 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5058 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005059 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5060 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005061 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5062 CK_BitCast, Arg);
5063 } else {
5064 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005065 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5066 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005067 if (HasLocalVariableExternalStorage(*I)) {
5068 QualType QT = (*I)->getType();
5069 QT = Context->getPointerType(QT);
5070 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5071 OK_Ordinary, SourceLocation());
5072 }
5073
5074 }
5075 InitExprs.push_back(Exp);
5076 }
5077 // Output all "by ref" declarations.
5078 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5079 E = BlockByRefDecls.end(); I != E; ++I) {
5080 ValueDecl *ND = (*I);
5081 std::string Name(ND->getNameAsString());
5082 std::string RecName;
5083 RewriteByRefString(RecName, Name, ND, true);
5084 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5085 + sizeof("struct"));
5086 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5087 SourceLocation(), SourceLocation(),
5088 II);
5089 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5090 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5091
5092 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005093 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005094 SourceLocation());
5095 bool isNestedCapturedVar = false;
5096 if (block)
5097 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5098 ce = block->capture_end(); ci != ce; ++ci) {
5099 const VarDecl *variable = ci->getVariable();
5100 if (variable == ND && ci->isNested()) {
5101 assert (ci->isByRef() &&
5102 "SynthBlockInitExpr - captured block variable is not byref");
5103 isNestedCapturedVar = true;
5104 break;
5105 }
5106 }
5107 // captured nested byref variable has its address passed. Do not take
5108 // its address again.
5109 if (!isNestedCapturedVar)
5110 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5111 Context->getPointerType(Exp->getType()),
5112 VK_RValue, OK_Ordinary, SourceLocation());
5113 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5114 InitExprs.push_back(Exp);
5115 }
5116 }
5117 if (ImportedBlockDecls.size()) {
5118 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5119 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5120 unsigned IntSize =
5121 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5122 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5123 Context->IntTy, SourceLocation());
5124 InitExprs.push_back(FlagExp);
5125 }
5126 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5127 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005128
5129 if (GlobalBlockExpr) {
5130 assert (GlobalConstructionExp == 0 &&
5131 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5132 GlobalConstructionExp = NewRep;
5133 NewRep = DRE;
5134 }
5135
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005136 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5137 Context->getPointerType(NewRep->getType()),
5138 VK_RValue, OK_Ordinary, SourceLocation());
5139 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5140 NewRep);
5141 BlockDeclRefs.clear();
5142 BlockByRefDecls.clear();
5143 BlockByRefDeclsPtrSet.clear();
5144 BlockByCopyDecls.clear();
5145 BlockByCopyDeclsPtrSet.clear();
5146 ImportedBlockDecls.clear();
5147 return NewRep;
5148}
5149
5150bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5151 if (const ObjCForCollectionStmt * CS =
5152 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5153 return CS->getElement() == DS;
5154 return false;
5155}
5156
5157//===----------------------------------------------------------------------===//
5158// Function Body / Expression rewriting
5159//===----------------------------------------------------------------------===//
5160
5161Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5162 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5163 isa<DoStmt>(S) || isa<ForStmt>(S))
5164 Stmts.push_back(S);
5165 else if (isa<ObjCForCollectionStmt>(S)) {
5166 Stmts.push_back(S);
5167 ObjCBcLabelNo.push_back(++BcLabelCount);
5168 }
5169
5170 // Pseudo-object operations and ivar references need special
5171 // treatment because we're going to recursively rewrite them.
5172 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5173 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5174 return RewritePropertyOrImplicitSetter(PseudoOp);
5175 } else {
5176 return RewritePropertyOrImplicitGetter(PseudoOp);
5177 }
5178 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5179 return RewriteObjCIvarRefExpr(IvarRefExpr);
5180 }
5181
5182 SourceRange OrigStmtRange = S->getSourceRange();
5183
5184 // Perform a bottom up rewrite of all children.
5185 for (Stmt::child_range CI = S->children(); CI; ++CI)
5186 if (*CI) {
5187 Stmt *childStmt = (*CI);
5188 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5189 if (newStmt) {
5190 *CI = newStmt;
5191 }
5192 }
5193
5194 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005195 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005196 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5197 InnerContexts.insert(BE->getBlockDecl());
5198 ImportedLocalExternalDecls.clear();
5199 GetInnerBlockDeclRefExprs(BE->getBody(),
5200 InnerBlockDeclRefs, InnerContexts);
5201 // Rewrite the block body in place.
5202 Stmt *SaveCurrentBody = CurrentBody;
5203 CurrentBody = BE->getBody();
5204 PropParentMap = 0;
5205 // block literal on rhs of a property-dot-sytax assignment
5206 // must be replaced by its synthesize ast so getRewrittenText
5207 // works as expected. In this case, what actually ends up on RHS
5208 // is the blockTranscribed which is the helper function for the
5209 // block literal; as in: self.c = ^() {[ace ARR];};
5210 bool saveDisableReplaceStmt = DisableReplaceStmt;
5211 DisableReplaceStmt = false;
5212 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5213 DisableReplaceStmt = saveDisableReplaceStmt;
5214 CurrentBody = SaveCurrentBody;
5215 PropParentMap = 0;
5216 ImportedLocalExternalDecls.clear();
5217 // Now we snarf the rewritten text and stash it away for later use.
5218 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5219 RewrittenBlockExprs[BE] = Str;
5220
5221 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5222
5223 //blockTranscribed->dump();
5224 ReplaceStmt(S, blockTranscribed);
5225 return blockTranscribed;
5226 }
5227 // Handle specific things.
5228 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5229 return RewriteAtEncode(AtEncode);
5230
5231 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5232 return RewriteAtSelector(AtSelector);
5233
5234 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5235 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005236
5237 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5238 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005239
Patrick Beardeb382ec2012-04-19 00:25:12 +00005240 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5241 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005242
5243 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5244 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005245
5246 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5247 dyn_cast<ObjCDictionaryLiteral>(S))
5248 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005249
5250 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5251#if 0
5252 // Before we rewrite it, put the original message expression in a comment.
5253 SourceLocation startLoc = MessExpr->getLocStart();
5254 SourceLocation endLoc = MessExpr->getLocEnd();
5255
5256 const char *startBuf = SM->getCharacterData(startLoc);
5257 const char *endBuf = SM->getCharacterData(endLoc);
5258
5259 std::string messString;
5260 messString += "// ";
5261 messString.append(startBuf, endBuf-startBuf+1);
5262 messString += "\n";
5263
5264 // FIXME: Missing definition of
5265 // InsertText(clang::SourceLocation, char const*, unsigned int).
5266 // InsertText(startLoc, messString.c_str(), messString.size());
5267 // Tried this, but it didn't work either...
5268 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5269#endif
5270 return RewriteMessageExpr(MessExpr);
5271 }
5272
5273 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5274 return RewriteObjCTryStmt(StmtTry);
5275
5276 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5277 return RewriteObjCSynchronizedStmt(StmtTry);
5278
5279 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5280 return RewriteObjCThrowStmt(StmtThrow);
5281
5282 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5283 return RewriteObjCProtocolExpr(ProtocolExp);
5284
5285 if (ObjCForCollectionStmt *StmtForCollection =
5286 dyn_cast<ObjCForCollectionStmt>(S))
5287 return RewriteObjCForCollectionStmt(StmtForCollection,
5288 OrigStmtRange.getEnd());
5289 if (BreakStmt *StmtBreakStmt =
5290 dyn_cast<BreakStmt>(S))
5291 return RewriteBreakStmt(StmtBreakStmt);
5292 if (ContinueStmt *StmtContinueStmt =
5293 dyn_cast<ContinueStmt>(S))
5294 return RewriteContinueStmt(StmtContinueStmt);
5295
5296 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5297 // and cast exprs.
5298 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5299 // FIXME: What we're doing here is modifying the type-specifier that
5300 // precedes the first Decl. In the future the DeclGroup should have
5301 // a separate type-specifier that we can rewrite.
5302 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5303 // the context of an ObjCForCollectionStmt. For example:
5304 // NSArray *someArray;
5305 // for (id <FooProtocol> index in someArray) ;
5306 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5307 // and it depends on the original text locations/positions.
5308 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5309 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5310
5311 // Blocks rewrite rules.
5312 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5313 DI != DE; ++DI) {
5314 Decl *SD = *DI;
5315 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5316 if (isTopLevelBlockPointerType(ND->getType()))
5317 RewriteBlockPointerDecl(ND);
5318 else if (ND->getType()->isFunctionPointerType())
5319 CheckFunctionPointerDecl(ND->getType(), ND);
5320 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5321 if (VD->hasAttr<BlocksAttr>()) {
5322 static unsigned uniqueByrefDeclCount = 0;
5323 assert(!BlockByRefDeclNo.count(ND) &&
5324 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5325 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5326 RewriteByRefVar(VD);
5327 }
5328 else
5329 RewriteTypeOfDecl(VD);
5330 }
5331 }
5332 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5333 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5334 RewriteBlockPointerDecl(TD);
5335 else if (TD->getUnderlyingType()->isFunctionPointerType())
5336 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5337 }
5338 }
5339 }
5340
5341 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5342 RewriteObjCQualifiedInterfaceTypes(CE);
5343
5344 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5345 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5346 assert(!Stmts.empty() && "Statement stack is empty");
5347 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5348 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5349 && "Statement stack mismatch");
5350 Stmts.pop_back();
5351 }
5352 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005353 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5354 ValueDecl *VD = DRE->getDecl();
5355 if (VD->hasAttr<BlocksAttr>())
5356 return RewriteBlockDeclRefExpr(DRE);
5357 if (HasLocalVariableExternalStorage(VD))
5358 return RewriteLocalVariableExternalStorage(DRE);
5359 }
5360
5361 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5362 if (CE->getCallee()->getType()->isBlockPointerType()) {
5363 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5364 ReplaceStmt(S, BlockCall);
5365 return BlockCall;
5366 }
5367 }
5368 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5369 RewriteCastExpr(CE);
5370 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005371 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5372 RewriteImplicitCastObjCExpr(ICE);
5373 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005374#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005375
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5377 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5378 ICE->getSubExpr(),
5379 SourceLocation());
5380 // Get the new text.
5381 std::string SStr;
5382 llvm::raw_string_ostream Buf(SStr);
5383 Replacement->printPretty(Buf, *Context);
5384 const std::string &Str = Buf.str();
5385
5386 printf("CAST = %s\n", &Str[0]);
5387 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5388 delete S;
5389 return Replacement;
5390 }
5391#endif
5392 // Return this stmt unmodified.
5393 return S;
5394}
5395
5396void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5397 for (RecordDecl::field_iterator i = RD->field_begin(),
5398 e = RD->field_end(); i != e; ++i) {
5399 FieldDecl *FD = *i;
5400 if (isTopLevelBlockPointerType(FD->getType()))
5401 RewriteBlockPointerDecl(FD);
5402 if (FD->getType()->isObjCQualifiedIdType() ||
5403 FD->getType()->isObjCQualifiedInterfaceType())
5404 RewriteObjCQualifiedInterfaceTypes(FD);
5405 }
5406}
5407
5408/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5409/// main file of the input.
5410void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5411 switch (D->getKind()) {
5412 case Decl::Function: {
5413 FunctionDecl *FD = cast<FunctionDecl>(D);
5414 if (FD->isOverloadedOperator())
5415 return;
5416
5417 // Since function prototypes don't have ParmDecl's, we check the function
5418 // prototype. This enables us to rewrite function declarations and
5419 // definitions using the same code.
5420 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5421
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005422 if (!FD->isThisDeclarationADefinition())
5423 break;
5424
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005425 // FIXME: If this should support Obj-C++, support CXXTryStmt
5426 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5427 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005428 CurrentBody = Body;
5429 Body =
5430 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5431 FD->setBody(Body);
5432 CurrentBody = 0;
5433 if (PropParentMap) {
5434 delete PropParentMap;
5435 PropParentMap = 0;
5436 }
5437 // This synthesizes and inserts the block "impl" struct, invoke function,
5438 // and any copy/dispose helper functions.
5439 InsertBlockLiteralsWithinFunction(FD);
5440 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005441 }
5442 break;
5443 }
5444 case Decl::ObjCMethod: {
5445 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5446 if (CompoundStmt *Body = MD->getCompoundBody()) {
5447 CurMethodDef = MD;
5448 CurrentBody = Body;
5449 Body =
5450 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5451 MD->setBody(Body);
5452 CurrentBody = 0;
5453 if (PropParentMap) {
5454 delete PropParentMap;
5455 PropParentMap = 0;
5456 }
5457 InsertBlockLiteralsWithinMethod(MD);
5458 CurMethodDef = 0;
5459 }
5460 break;
5461 }
5462 case Decl::ObjCImplementation: {
5463 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5464 ClassImplementation.push_back(CI);
5465 break;
5466 }
5467 case Decl::ObjCCategoryImpl: {
5468 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5469 CategoryImplementation.push_back(CI);
5470 break;
5471 }
5472 case Decl::Var: {
5473 VarDecl *VD = cast<VarDecl>(D);
5474 RewriteObjCQualifiedInterfaceTypes(VD);
5475 if (isTopLevelBlockPointerType(VD->getType()))
5476 RewriteBlockPointerDecl(VD);
5477 else if (VD->getType()->isFunctionPointerType()) {
5478 CheckFunctionPointerDecl(VD->getType(), VD);
5479 if (VD->getInit()) {
5480 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5481 RewriteCastExpr(CE);
5482 }
5483 }
5484 } else if (VD->getType()->isRecordType()) {
5485 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5486 if (RD->isCompleteDefinition())
5487 RewriteRecordBody(RD);
5488 }
5489 if (VD->getInit()) {
5490 GlobalVarDecl = VD;
5491 CurrentBody = VD->getInit();
5492 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5493 CurrentBody = 0;
5494 if (PropParentMap) {
5495 delete PropParentMap;
5496 PropParentMap = 0;
5497 }
5498 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5499 GlobalVarDecl = 0;
5500
5501 // This is needed for blocks.
5502 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5503 RewriteCastExpr(CE);
5504 }
5505 }
5506 break;
5507 }
5508 case Decl::TypeAlias:
5509 case Decl::Typedef: {
5510 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5511 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5512 RewriteBlockPointerDecl(TD);
5513 else if (TD->getUnderlyingType()->isFunctionPointerType())
5514 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5515 }
5516 break;
5517 }
5518 case Decl::CXXRecord:
5519 case Decl::Record: {
5520 RecordDecl *RD = cast<RecordDecl>(D);
5521 if (RD->isCompleteDefinition())
5522 RewriteRecordBody(RD);
5523 break;
5524 }
5525 default:
5526 break;
5527 }
5528 // Nothing yet.
5529}
5530
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005531/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5532/// protocol reference symbols in the for of:
5533/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5534static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5535 ObjCProtocolDecl *PDecl,
5536 std::string &Result) {
5537 // Also output .objc_protorefs$B section and its meta-data.
5538 if (Context->getLangOpts().MicrosoftExt)
5539 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5540 Result += "struct _protocol_t *";
5541 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5542 Result += PDecl->getNameAsString();
5543 Result += " = &";
5544 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5545 Result += ";\n";
5546}
5547
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005548void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5549 if (Diags.hasErrorOccurred())
5550 return;
5551
5552 RewriteInclude();
5553
5554 // Here's a great place to add any extra declarations that may be needed.
5555 // Write out meta data for each @protocol(<expr>).
5556 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005557 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005558 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005559 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5560 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005561
5562 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005563 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5564 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5565 // Write struct declaration for the class matching its ivar declarations.
5566 // Note that for modern abi, this is postponed until the end of TU
5567 // because class extensions and the implementation might declare their own
5568 // private ivars.
5569 RewriteInterfaceDecl(CDecl);
5570 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005571
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005572 if (ClassImplementation.size() || CategoryImplementation.size())
5573 RewriteImplementations();
5574
5575 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5576 // we are done.
5577 if (const RewriteBuffer *RewriteBuf =
5578 Rewrite.getRewriteBufferFor(MainFileID)) {
5579 //printf("Changed:\n");
5580 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5581 } else {
5582 llvm::errs() << "No changes\n";
5583 }
5584
5585 if (ClassImplementation.size() || CategoryImplementation.size() ||
5586 ProtocolExprDecls.size()) {
5587 // Rewrite Objective-c meta data*
5588 std::string ResultStr;
5589 RewriteMetaDataIntoBuffer(ResultStr);
5590 // Emit metadata.
5591 *OutFile << ResultStr;
5592 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005593 // Emit ImageInfo;
5594 {
5595 std::string ResultStr;
5596 WriteImageInfo(ResultStr);
5597 *OutFile << ResultStr;
5598 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005599 OutFile->flush();
5600}
5601
5602void RewriteModernObjC::Initialize(ASTContext &context) {
5603 InitializeCommon(context);
5604
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005605 Preamble += "#ifndef __OBJC2__\n";
5606 Preamble += "#define __OBJC2__\n";
5607 Preamble += "#endif\n";
5608
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005609 // declaring objc_selector outside the parameter list removes a silly
5610 // scope related warning...
5611 if (IsHeader)
5612 Preamble = "#pragma once\n";
5613 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005614 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5615 Preamble += "\n\tstruct objc_object *superClass; ";
5616 // Add a constructor for creating temporary objects.
5617 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5618 Preamble += ": object(o), superClass(s) {} ";
5619 Preamble += "\n};\n";
5620
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005621 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005622 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005623 // These are currently generated.
5624 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005625 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005626 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005627 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5628 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005629 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005630 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005631 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005632 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5633 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005634 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005635
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005636 // These need be generated for performance. Currently they are not,
5637 // using API calls instead.
5638 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5639 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5640 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5641
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005642 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005643 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5644 Preamble += "typedef struct objc_object Protocol;\n";
5645 Preamble += "#define _REWRITER_typedef_Protocol\n";
5646 Preamble += "#endif\n";
5647 if (LangOpts.MicrosoftExt) {
5648 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5649 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005650 }
5651 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005652 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005653
5654 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5655 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5656 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5657 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5658 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5659
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005660 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5661 Preamble += "(const char *);\n";
5662 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5663 Preamble += "(struct objc_class *);\n";
5664 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5665 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005666 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005667 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005668 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5669 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005670 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5671 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5672 Preamble += "struct __objcFastEnumerationState {\n\t";
5673 Preamble += "unsigned long state;\n\t";
5674 Preamble += "void **itemsPtr;\n\t";
5675 Preamble += "unsigned long *mutationsPtr;\n\t";
5676 Preamble += "unsigned long extra[5];\n};\n";
5677 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5678 Preamble += "#define __FASTENUMERATIONSTATE\n";
5679 Preamble += "#endif\n";
5680 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5681 Preamble += "struct __NSConstantStringImpl {\n";
5682 Preamble += " int *isa;\n";
5683 Preamble += " int flags;\n";
5684 Preamble += " char *str;\n";
5685 Preamble += " long length;\n";
5686 Preamble += "};\n";
5687 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5688 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5689 Preamble += "#else\n";
5690 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5691 Preamble += "#endif\n";
5692 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5693 Preamble += "#endif\n";
5694 // Blocks preamble.
5695 Preamble += "#ifndef BLOCK_IMPL\n";
5696 Preamble += "#define BLOCK_IMPL\n";
5697 Preamble += "struct __block_impl {\n";
5698 Preamble += " void *isa;\n";
5699 Preamble += " int Flags;\n";
5700 Preamble += " int Reserved;\n";
5701 Preamble += " void *FuncPtr;\n";
5702 Preamble += "};\n";
5703 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5704 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5705 Preamble += "extern \"C\" __declspec(dllexport) "
5706 "void _Block_object_assign(void *, const void *, const int);\n";
5707 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5708 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5709 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5710 Preamble += "#else\n";
5711 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5712 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5713 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5714 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5715 Preamble += "#endif\n";
5716 Preamble += "#endif\n";
5717 if (LangOpts.MicrosoftExt) {
5718 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5719 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5720 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5721 Preamble += "#define __attribute__(X)\n";
5722 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005723 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005724 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005725 Preamble += "#endif\n";
5726 Preamble += "#ifndef __block\n";
5727 Preamble += "#define __block\n";
5728 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005729 }
5730 else {
5731 Preamble += "#define __block\n";
5732 Preamble += "#define __weak\n";
5733 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005734
5735 // Declarations required for modern objective-c array and dictionary literals.
5736 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005737 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005738 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005739 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005740 Preamble += "\tva_list marker;\n";
5741 Preamble += "\tva_start(marker, count);\n";
5742 Preamble += "\tarr = new void *[count];\n";
5743 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5744 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5745 Preamble += "\tva_end( marker );\n";
5746 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005747 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005748 Preamble += "\tdelete[] arr;\n";
5749 Preamble += " }\n";
5750 Preamble += "};\n";
5751
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005752 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5753 // as this avoids warning in any 64bit/32bit compilation model.
5754 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5755}
5756
5757/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5758/// ivar offset.
5759void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5760 std::string &Result) {
5761 if (ivar->isBitField()) {
5762 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5763 // place all bitfields at offset 0.
5764 Result += "0";
5765 } else {
5766 Result += "__OFFSETOFIVAR__(struct ";
5767 Result += ivar->getContainingInterface()->getNameAsString();
5768 if (LangOpts.MicrosoftExt)
5769 Result += "_IMPL";
5770 Result += ", ";
5771 Result += ivar->getNameAsString();
5772 Result += ")";
5773 }
5774}
5775
5776/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5777/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005778/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005779/// char *attributes;
5780/// }
5781
5782/// struct _prop_list_t {
5783/// uint32_t entsize; // sizeof(struct _prop_t)
5784/// uint32_t count_of_properties;
5785/// struct _prop_t prop_list[count_of_properties];
5786/// }
5787
5788/// struct _protocol_t;
5789
5790/// struct _protocol_list_t {
5791/// long protocol_count; // Note, this is 32/64 bit
5792/// struct _protocol_t * protocol_list[protocol_count];
5793/// }
5794
5795/// struct _objc_method {
5796/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005797/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005798/// char *_imp;
5799/// }
5800
5801/// struct _method_list_t {
5802/// uint32_t entsize; // sizeof(struct _objc_method)
5803/// uint32_t method_count;
5804/// struct _objc_method method_list[method_count];
5805/// }
5806
5807/// struct _protocol_t {
5808/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005809/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005810/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005811/// const struct method_list_t *instance_methods;
5812/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005813/// const struct method_list_t *optionalInstanceMethods;
5814/// const struct method_list_t *optionalClassMethods;
5815/// const struct _prop_list_t * properties;
5816/// const uint32_t size; // sizeof(struct _protocol_t)
5817/// const uint32_t flags; // = 0
5818/// const char ** extendedMethodTypes;
5819/// }
5820
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005821/// struct _ivar_t {
5822/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005823/// const char *name;
5824/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005825/// uint32_t alignment;
5826/// uint32_t size;
5827/// }
5828
5829/// struct _ivar_list_t {
5830/// uint32 entsize; // sizeof(struct _ivar_t)
5831/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005832/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005833/// }
5834
5835/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005836/// uint32_t flags;
5837/// uint32_t instanceStart;
5838/// uint32_t instanceSize;
5839/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005840/// const uint8_t *ivarLayout;
5841/// const char *name;
5842/// const struct _method_list_t *baseMethods;
5843/// const struct _protocol_list_t *baseProtocols;
5844/// const struct _ivar_list_t *ivars;
5845/// const uint8_t *weakIvarLayout;
5846/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005847/// }
5848
5849/// struct _class_t {
5850/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005851/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005852/// void *cache;
5853/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005854/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005855/// }
5856
5857/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005858/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005859/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005860/// const struct _method_list_t *instance_methods;
5861/// const struct _method_list_t *class_methods;
5862/// const struct _protocol_list_t *protocols;
5863/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005864/// }
5865
5866/// MessageRefTy - LLVM for:
5867/// struct _message_ref_t {
5868/// IMP messenger;
5869/// SEL name;
5870/// };
5871
5872/// SuperMessageRefTy - LLVM for:
5873/// struct _super_message_ref_t {
5874/// SUPER_IMP messenger;
5875/// SEL name;
5876/// };
5877
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005878static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005879 static bool meta_data_declared = false;
5880 if (meta_data_declared)
5881 return;
5882
5883 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005884 Result += "\tconst char *name;\n";
5885 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005886 Result += "};\n";
5887
5888 Result += "\nstruct _protocol_t;\n";
5889
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005890 Result += "\nstruct _objc_method {\n";
5891 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005892 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005893 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005894 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005895
5896 Result += "\nstruct _protocol_t {\n";
5897 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005898 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005899 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005900 Result += "\tconst struct method_list_t *instance_methods;\n";
5901 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005902 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5903 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5904 Result += "\tconst struct _prop_list_t * properties;\n";
5905 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5906 Result += "\tconst unsigned int flags; // = 0\n";
5907 Result += "\tconst char ** extendedMethodTypes;\n";
5908 Result += "};\n";
5909
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005910 Result += "\nstruct _ivar_t {\n";
5911 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005912 Result += "\tconst char *name;\n";
5913 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005914 Result += "\tunsigned int alignment;\n";
5915 Result += "\tunsigned int size;\n";
5916 Result += "};\n";
5917
5918 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005919 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005920 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005921 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005922 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5923 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005924 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005925 Result += "\tconst unsigned char *ivarLayout;\n";
5926 Result += "\tconst char *name;\n";
5927 Result += "\tconst struct _method_list_t *baseMethods;\n";
5928 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5929 Result += "\tconst struct _ivar_list_t *ivars;\n";
5930 Result += "\tconst unsigned char *weakIvarLayout;\n";
5931 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005932 Result += "};\n";
5933
5934 Result += "\nstruct _class_t {\n";
5935 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005936 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005937 Result += "\tvoid *cache;\n";
5938 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005939 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005940 Result += "};\n";
5941
5942 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005943 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005944 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005945 Result += "\tconst struct _method_list_t *instance_methods;\n";
5946 Result += "\tconst struct _method_list_t *class_methods;\n";
5947 Result += "\tconst struct _protocol_list_t *protocols;\n";
5948 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005949 Result += "};\n";
5950
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005951 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005952 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005953 meta_data_declared = true;
5954}
5955
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005956static void Write_protocol_list_t_TypeDecl(std::string &Result,
5957 long super_protocol_count) {
5958 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5959 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5960 Result += "\tstruct _protocol_t *super_protocols[";
5961 Result += utostr(super_protocol_count); Result += "];\n";
5962 Result += "}";
5963}
5964
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005965static void Write_method_list_t_TypeDecl(std::string &Result,
5966 unsigned int method_count) {
5967 Result += "struct /*_method_list_t*/"; Result += " {\n";
5968 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5969 Result += "\tunsigned int method_count;\n";
5970 Result += "\tstruct _objc_method method_list[";
5971 Result += utostr(method_count); Result += "];\n";
5972 Result += "}";
5973}
5974
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005975static void Write__prop_list_t_TypeDecl(std::string &Result,
5976 unsigned int property_count) {
5977 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5978 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5979 Result += "\tunsigned int count_of_properties;\n";
5980 Result += "\tstruct _prop_t prop_list[";
5981 Result += utostr(property_count); Result += "];\n";
5982 Result += "}";
5983}
5984
Fariborz Jahanianae932952012-02-10 20:47:10 +00005985static void Write__ivar_list_t_TypeDecl(std::string &Result,
5986 unsigned int ivar_count) {
5987 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5988 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5989 Result += "\tunsigned int count;\n";
5990 Result += "\tstruct _ivar_t ivar_list[";
5991 Result += utostr(ivar_count); Result += "];\n";
5992 Result += "}";
5993}
5994
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005995static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5996 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5997 StringRef VarName,
5998 StringRef ProtocolName) {
5999 if (SuperProtocols.size() > 0) {
6000 Result += "\nstatic ";
6001 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6002 Result += " "; Result += VarName;
6003 Result += ProtocolName;
6004 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6005 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6006 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6007 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6008 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6009 Result += SuperPD->getNameAsString();
6010 if (i == e-1)
6011 Result += "\n};\n";
6012 else
6013 Result += ",\n";
6014 }
6015 }
6016}
6017
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006018static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6019 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006020 ArrayRef<ObjCMethodDecl *> Methods,
6021 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006022 StringRef TopLevelDeclName,
6023 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006024 if (Methods.size() > 0) {
6025 Result += "\nstatic ";
6026 Write_method_list_t_TypeDecl(Result, Methods.size());
6027 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006028 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006029 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6030 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6031 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6032 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6033 ObjCMethodDecl *MD = Methods[i];
6034 if (i == 0)
6035 Result += "\t{{(struct objc_selector *)\"";
6036 else
6037 Result += "\t{(struct objc_selector *)\"";
6038 Result += (MD)->getSelector().getAsString(); Result += "\"";
6039 Result += ", ";
6040 std::string MethodTypeString;
6041 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6042 Result += "\""; Result += MethodTypeString; Result += "\"";
6043 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006044 if (!MethodImpl)
6045 Result += "0";
6046 else {
6047 Result += "(void *)";
6048 Result += RewriteObj.MethodInternalNames[MD];
6049 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006050 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006051 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006052 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006053 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006054 }
6055 Result += "};\n";
6056 }
6057}
6058
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006059static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006060 ASTContext *Context, std::string &Result,
6061 ArrayRef<ObjCPropertyDecl *> Properties,
6062 const Decl *Container,
6063 StringRef VarName,
6064 StringRef ProtocolName) {
6065 if (Properties.size() > 0) {
6066 Result += "\nstatic ";
6067 Write__prop_list_t_TypeDecl(Result, Properties.size());
6068 Result += " "; Result += VarName;
6069 Result += ProtocolName;
6070 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6071 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6072 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6073 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6074 ObjCPropertyDecl *PropDecl = Properties[i];
6075 if (i == 0)
6076 Result += "\t{{\"";
6077 else
6078 Result += "\t{\"";
6079 Result += PropDecl->getName(); Result += "\",";
6080 std::string PropertyTypeString, QuotePropertyTypeString;
6081 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6082 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6083 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6084 if (i == e-1)
6085 Result += "}}\n";
6086 else
6087 Result += "},\n";
6088 }
6089 Result += "};\n";
6090 }
6091}
6092
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006093// Metadata flags
6094enum MetaDataDlags {
6095 CLS = 0x0,
6096 CLS_META = 0x1,
6097 CLS_ROOT = 0x2,
6098 OBJC2_CLS_HIDDEN = 0x10,
6099 CLS_EXCEPTION = 0x20,
6100
6101 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6102 CLS_HAS_IVAR_RELEASER = 0x40,
6103 /// class was compiled with -fobjc-arr
6104 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6105};
6106
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006107static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6108 unsigned int flags,
6109 const std::string &InstanceStart,
6110 const std::string &InstanceSize,
6111 ArrayRef<ObjCMethodDecl *>baseMethods,
6112 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6113 ArrayRef<ObjCIvarDecl *>ivars,
6114 ArrayRef<ObjCPropertyDecl *>Properties,
6115 StringRef VarName,
6116 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006117 Result += "\nstatic struct _class_ro_t ";
6118 Result += VarName; Result += ClassName;
6119 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6120 Result += "\t";
6121 Result += llvm::utostr(flags); Result += ", ";
6122 Result += InstanceStart; Result += ", ";
6123 Result += InstanceSize; Result += ", \n";
6124 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006125 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6126 if (Triple.getArch() == llvm::Triple::x86_64)
6127 // uint32_t const reserved; // only when building for 64bit targets
6128 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006129 // const uint8_t * const ivarLayout;
6130 Result += "0, \n\t";
6131 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006132 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006133 if (baseMethods.size() > 0) {
6134 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006135 if (metaclass)
6136 Result += "_OBJC_$_CLASS_METHODS_";
6137 else
6138 Result += "_OBJC_$_INSTANCE_METHODS_";
6139 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006140 Result += ",\n\t";
6141 }
6142 else
6143 Result += "0, \n\t";
6144
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006145 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006146 Result += "(const struct _objc_protocol_list *)&";
6147 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6148 Result += ",\n\t";
6149 }
6150 else
6151 Result += "0, \n\t";
6152
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006153 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006154 Result += "(const struct _ivar_list_t *)&";
6155 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6156 Result += ",\n\t";
6157 }
6158 else
6159 Result += "0, \n\t";
6160
6161 // weakIvarLayout
6162 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006163 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006164 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006165 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006166 Result += ",\n";
6167 }
6168 else
6169 Result += "0, \n";
6170
6171 Result += "};\n";
6172}
6173
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006174static void Write_class_t(ASTContext *Context, std::string &Result,
6175 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006176 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6177 bool rootClass = (!CDecl->getSuperClass());
6178 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006179
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006180 if (!rootClass) {
6181 // Find the Root class
6182 RootClass = CDecl->getSuperClass();
6183 while (RootClass->getSuperClass()) {
6184 RootClass = RootClass->getSuperClass();
6185 }
6186 }
6187
6188 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006189 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006190 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006191 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006192 if (CDecl->getImplementation())
6193 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006194 else
6195 Result += "__declspec(dllimport) ";
6196
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006197 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006198 Result += CDecl->getNameAsString();
6199 Result += ";\n";
6200 }
6201 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006202 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006203 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006204 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006205 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006206 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006207 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006208 else
6209 Result += "__declspec(dllimport) ";
6210
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006211 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006212 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006213 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006214 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006215
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006216 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006217 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006218 if (RootClass->getImplementation())
6219 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006220 else
6221 Result += "__declspec(dllimport) ";
6222
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006223 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006224 Result += VarName;
6225 Result += RootClass->getNameAsString();
6226 Result += ";\n";
6227 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006228 }
6229
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006230 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6231 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006232 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6233 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006234 if (metaclass) {
6235 if (!rootClass) {
6236 Result += "0, // &"; Result += VarName;
6237 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006238 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006239 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006240 Result += CDecl->getSuperClass()->getNameAsString();
6241 Result += ",\n\t";
6242 }
6243 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006244 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006245 Result += CDecl->getNameAsString();
6246 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006247 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006248 Result += ",\n\t";
6249 }
6250 }
6251 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006252 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006253 Result += CDecl->getNameAsString();
6254 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006255 if (!rootClass) {
6256 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006257 Result += CDecl->getSuperClass()->getNameAsString();
6258 Result += ",\n\t";
6259 }
6260 else
6261 Result += "0,\n\t";
6262 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006263 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6264 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6265 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006266 Result += "&_OBJC_METACLASS_RO_$_";
6267 else
6268 Result += "&_OBJC_CLASS_RO_$_";
6269 Result += CDecl->getNameAsString();
6270 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006271
6272 // Add static function to initialize some of the meta-data fields.
6273 // avoid doing it twice.
6274 if (metaclass)
6275 return;
6276
6277 const ObjCInterfaceDecl *SuperClass =
6278 rootClass ? CDecl : CDecl->getSuperClass();
6279
6280 Result += "static void OBJC_CLASS_SETUP_$_";
6281 Result += CDecl->getNameAsString();
6282 Result += "(void ) {\n";
6283 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6284 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006285 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006286
6287 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006288 Result += ".superclass = ";
6289 if (rootClass)
6290 Result += "&OBJC_CLASS_$_";
6291 else
6292 Result += "&OBJC_METACLASS_$_";
6293
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006294 Result += SuperClass->getNameAsString(); Result += ";\n";
6295
6296 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6297 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6298
6299 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6300 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6301 Result += CDecl->getNameAsString(); Result += ";\n";
6302
6303 if (!rootClass) {
6304 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6305 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6306 Result += SuperClass->getNameAsString(); Result += ";\n";
6307 }
6308
6309 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6310 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6311 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006312}
6313
Fariborz Jahanian61186122012-02-17 18:40:41 +00006314static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6315 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006316 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006317 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006318 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6319 ArrayRef<ObjCMethodDecl *> ClassMethods,
6320 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6321 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006322 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006323 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006324 // must declare an extern class object in case this class is not implemented
6325 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006326 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006327 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006328 if (ClassDecl->getImplementation())
6329 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006330 else
6331 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006332
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006333 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006334 Result += "OBJC_CLASS_$_"; Result += ClassName;
6335 Result += ";\n";
6336
Fariborz Jahanian61186122012-02-17 18:40:41 +00006337 Result += "\nstatic struct _category_t ";
6338 Result += "_OBJC_$_CATEGORY_";
6339 Result += ClassName; Result += "_$_"; Result += CatName;
6340 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6341 Result += "{\n";
6342 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006343 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006344 Result += ",\n";
6345 if (InstanceMethods.size() > 0) {
6346 Result += "\t(const struct _method_list_t *)&";
6347 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6348 Result += ClassName; Result += "_$_"; Result += CatName;
6349 Result += ",\n";
6350 }
6351 else
6352 Result += "\t0,\n";
6353
6354 if (ClassMethods.size() > 0) {
6355 Result += "\t(const struct _method_list_t *)&";
6356 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6357 Result += ClassName; Result += "_$_"; Result += CatName;
6358 Result += ",\n";
6359 }
6360 else
6361 Result += "\t0,\n";
6362
6363 if (RefedProtocols.size() > 0) {
6364 Result += "\t(const struct _protocol_list_t *)&";
6365 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6366 Result += ClassName; Result += "_$_"; Result += CatName;
6367 Result += ",\n";
6368 }
6369 else
6370 Result += "\t0,\n";
6371
6372 if (ClassProperties.size() > 0) {
6373 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6374 Result += ClassName; Result += "_$_"; Result += CatName;
6375 Result += ",\n";
6376 }
6377 else
6378 Result += "\t0,\n";
6379
6380 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006381
6382 // Add static function to initialize the class pointer in the category structure.
6383 Result += "static void OBJC_CATEGORY_SETUP_$_";
6384 Result += ClassDecl->getNameAsString();
6385 Result += "_$_";
6386 Result += CatName;
6387 Result += "(void ) {\n";
6388 Result += "\t_OBJC_$_CATEGORY_";
6389 Result += ClassDecl->getNameAsString();
6390 Result += "_$_";
6391 Result += CatName;
6392 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6393 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006394}
6395
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006396static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6397 ASTContext *Context, std::string &Result,
6398 ArrayRef<ObjCMethodDecl *> Methods,
6399 StringRef VarName,
6400 StringRef ProtocolName) {
6401 if (Methods.size() == 0)
6402 return;
6403
6404 Result += "\nstatic const char *";
6405 Result += VarName; Result += ProtocolName;
6406 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6407 Result += "{\n";
6408 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6409 ObjCMethodDecl *MD = Methods[i];
6410 std::string MethodTypeString, QuoteMethodTypeString;
6411 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6412 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6413 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6414 if (i == e-1)
6415 Result += "\n};\n";
6416 else {
6417 Result += ",\n";
6418 }
6419 }
6420}
6421
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006422static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6423 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006424 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006425 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006426 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006427 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6428 // this is what happens:
6429 /**
6430 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6431 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6432 Class->getVisibility() == HiddenVisibility)
6433 Visibility shoud be: HiddenVisibility;
6434 else
6435 Visibility shoud be: DefaultVisibility;
6436 */
6437
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006438 Result += "\n";
6439 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6440 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006441 if (Context->getLangOpts().MicrosoftExt)
6442 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6443
6444 if (!Context->getLangOpts().MicrosoftExt ||
6445 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006446 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006447 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006448 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006449 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006450 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006451 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6452 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006453 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6454 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006455 }
6456}
6457
Fariborz Jahanianae932952012-02-10 20:47:10 +00006458static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6459 ASTContext *Context, std::string &Result,
6460 ArrayRef<ObjCIvarDecl *> Ivars,
6461 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006462 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006463 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006464 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006465
Fariborz Jahanianae932952012-02-10 20:47:10 +00006466 Result += "\nstatic ";
6467 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6468 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006469 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006470 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6471 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6472 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6473 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6474 ObjCIvarDecl *IvarDecl = Ivars[i];
6475 if (i == 0)
6476 Result += "\t{{";
6477 else
6478 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006479 Result += "(unsigned long int *)&";
6480 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006481 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006482
6483 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6484 std::string IvarTypeString, QuoteIvarTypeString;
6485 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6486 IvarDecl);
6487 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6488 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6489
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006490 // FIXME. this alignment represents the host alignment and need be changed to
6491 // represent the target alignment.
6492 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6493 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006494 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006495 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6496 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006497 if (i == e-1)
6498 Result += "}}\n";
6499 else
6500 Result += "},\n";
6501 }
6502 Result += "};\n";
6503 }
6504}
6505
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006506/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006507void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6508 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006509
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006510 // Do not synthesize the protocol more than once.
6511 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6512 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006513 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006514
6515 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6516 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006517 // Must write out all protocol definitions in current qualifier list,
6518 // and in their nested qualifiers before writing out current definition.
6519 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6520 E = PDecl->protocol_end(); I != E; ++I)
6521 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006522
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006523 // Construct method lists.
6524 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6525 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6526 for (ObjCProtocolDecl::instmeth_iterator
6527 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6528 I != E; ++I) {
6529 ObjCMethodDecl *MD = *I;
6530 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6531 OptInstanceMethods.push_back(MD);
6532 } else {
6533 InstanceMethods.push_back(MD);
6534 }
6535 }
6536
6537 for (ObjCProtocolDecl::classmeth_iterator
6538 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6539 I != E; ++I) {
6540 ObjCMethodDecl *MD = *I;
6541 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6542 OptClassMethods.push_back(MD);
6543 } else {
6544 ClassMethods.push_back(MD);
6545 }
6546 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006547 std::vector<ObjCMethodDecl *> AllMethods;
6548 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6549 AllMethods.push_back(InstanceMethods[i]);
6550 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6551 AllMethods.push_back(ClassMethods[i]);
6552 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6553 AllMethods.push_back(OptInstanceMethods[i]);
6554 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6555 AllMethods.push_back(OptClassMethods[i]);
6556
6557 Write__extendedMethodTypes_initializer(*this, Context, Result,
6558 AllMethods,
6559 "_OBJC_PROTOCOL_METHOD_TYPES_",
6560 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006561 // Protocol's super protocol list
6562 std::vector<ObjCProtocolDecl *> SuperProtocols;
6563 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6564 E = PDecl->protocol_end(); I != E; ++I)
6565 SuperProtocols.push_back(*I);
6566
6567 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6568 "_OBJC_PROTOCOL_REFS_",
6569 PDecl->getNameAsString());
6570
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006571 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006572 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006573 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006574
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006575 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006576 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006577 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006578
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006579 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006580 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006581 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006582
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006583 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006584 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006585 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006586
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006587 // Protocol's property metadata.
6588 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6589 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6590 E = PDecl->prop_end(); I != E; ++I)
6591 ProtocolProperties.push_back(*I);
6592
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006593 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006594 /* Container */0,
6595 "_OBJC_PROTOCOL_PROPERTIES_",
6596 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006597
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006598 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006599 Result += "\n";
6600 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006601 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006602 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006603 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006604 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6605 Result += "\t0,\n"; // id is; is null
6606 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006607 if (SuperProtocols.size() > 0) {
6608 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6609 Result += PDecl->getNameAsString(); Result += ",\n";
6610 }
6611 else
6612 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006613 if (InstanceMethods.size() > 0) {
6614 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6615 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006616 }
6617 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006618 Result += "\t0,\n";
6619
6620 if (ClassMethods.size() > 0) {
6621 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6622 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006623 }
6624 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006625 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006626
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006627 if (OptInstanceMethods.size() > 0) {
6628 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6629 Result += PDecl->getNameAsString(); Result += ",\n";
6630 }
6631 else
6632 Result += "\t0,\n";
6633
6634 if (OptClassMethods.size() > 0) {
6635 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6636 Result += PDecl->getNameAsString(); Result += ",\n";
6637 }
6638 else
6639 Result += "\t0,\n";
6640
6641 if (ProtocolProperties.size() > 0) {
6642 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6643 Result += PDecl->getNameAsString(); Result += ",\n";
6644 }
6645 else
6646 Result += "\t0,\n";
6647
6648 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6649 Result += "\t0,\n";
6650
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006651 if (AllMethods.size() > 0) {
6652 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6653 Result += PDecl->getNameAsString();
6654 Result += "\n};\n";
6655 }
6656 else
6657 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006658
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006659 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006660 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006661 Result += "struct _protocol_t *";
6662 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6663 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6664 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006665
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006666 // Mark this protocol as having been generated.
6667 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6668 llvm_unreachable("protocol already synthesized");
6669
6670}
6671
6672void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6673 const ObjCList<ObjCProtocolDecl> &Protocols,
6674 StringRef prefix, StringRef ClassName,
6675 std::string &Result) {
6676 if (Protocols.empty()) return;
6677
6678 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006679 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006680
6681 // Output the top lovel protocol meta-data for the class.
6682 /* struct _objc_protocol_list {
6683 struct _objc_protocol_list *next;
6684 int protocol_count;
6685 struct _objc_protocol *class_protocols[];
6686 }
6687 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006688 Result += "\n";
6689 if (LangOpts.MicrosoftExt)
6690 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6691 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006692 Result += "\tstruct _objc_protocol_list *next;\n";
6693 Result += "\tint protocol_count;\n";
6694 Result += "\tstruct _objc_protocol *class_protocols[";
6695 Result += utostr(Protocols.size());
6696 Result += "];\n} _OBJC_";
6697 Result += prefix;
6698 Result += "_PROTOCOLS_";
6699 Result += ClassName;
6700 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6701 "{\n\t0, ";
6702 Result += utostr(Protocols.size());
6703 Result += "\n";
6704
6705 Result += "\t,{&_OBJC_PROTOCOL_";
6706 Result += Protocols[0]->getNameAsString();
6707 Result += " \n";
6708
6709 for (unsigned i = 1; i != Protocols.size(); i++) {
6710 Result += "\t ,&_OBJC_PROTOCOL_";
6711 Result += Protocols[i]->getNameAsString();
6712 Result += "\n";
6713 }
6714 Result += "\t }\n};\n";
6715}
6716
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006717/// hasObjCExceptionAttribute - Return true if this class or any super
6718/// class has the __objc_exception__ attribute.
6719/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6720static bool hasObjCExceptionAttribute(ASTContext &Context,
6721 const ObjCInterfaceDecl *OID) {
6722 if (OID->hasAttr<ObjCExceptionAttr>())
6723 return true;
6724 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6725 return hasObjCExceptionAttribute(Context, Super);
6726 return false;
6727}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006728
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006729void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6730 std::string &Result) {
6731 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6732
6733 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006734 if (CDecl->isImplicitInterfaceDecl())
6735 assert(false &&
6736 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006737
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006738 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006739 SmallVector<ObjCIvarDecl *, 8> IVars;
6740
6741 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6742 IVD; IVD = IVD->getNextIvar()) {
6743 // Ignore unnamed bit-fields.
6744 if (!IVD->getDeclName())
6745 continue;
6746 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006747 }
6748
Fariborz Jahanianae932952012-02-10 20:47:10 +00006749 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006750 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006751 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006752
6753 // Build _objc_method_list for class's instance methods if needed
6754 SmallVector<ObjCMethodDecl *, 32>
6755 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6756
6757 // If any of our property implementations have associated getters or
6758 // setters, produce metadata for them as well.
6759 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6760 PropEnd = IDecl->propimpl_end();
6761 Prop != PropEnd; ++Prop) {
6762 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6763 continue;
6764 if (!(*Prop)->getPropertyIvarDecl())
6765 continue;
6766 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6767 if (!PD)
6768 continue;
6769 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6770 if (!Getter->isDefined())
6771 InstanceMethods.push_back(Getter);
6772 if (PD->isReadOnly())
6773 continue;
6774 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6775 if (!Setter->isDefined())
6776 InstanceMethods.push_back(Setter);
6777 }
6778
6779 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6780 "_OBJC_$_INSTANCE_METHODS_",
6781 IDecl->getNameAsString(), true);
6782
6783 SmallVector<ObjCMethodDecl *, 32>
6784 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6785
6786 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6787 "_OBJC_$_CLASS_METHODS_",
6788 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006789
6790 // Protocols referenced in class declaration?
6791 // Protocol's super protocol list
6792 std::vector<ObjCProtocolDecl *> RefedProtocols;
6793 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6794 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6795 E = Protocols.end();
6796 I != E; ++I) {
6797 RefedProtocols.push_back(*I);
6798 // Must write out all protocol definitions in current qualifier list,
6799 // and in their nested qualifiers before writing out current definition.
6800 RewriteObjCProtocolMetaData(*I, Result);
6801 }
6802
6803 Write_protocol_list_initializer(Context, Result,
6804 RefedProtocols,
6805 "_OBJC_CLASS_PROTOCOLS_$_",
6806 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006807
6808 // Protocol's property metadata.
6809 std::vector<ObjCPropertyDecl *> ClassProperties;
6810 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6811 E = CDecl->prop_end(); I != E; ++I)
6812 ClassProperties.push_back(*I);
6813
6814 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006815 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006816 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006817 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006818
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006819
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006820 // Data for initializing _class_ro_t metaclass meta-data
6821 uint32_t flags = CLS_META;
6822 std::string InstanceSize;
6823 std::string InstanceStart;
6824
6825
6826 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6827 if (classIsHidden)
6828 flags |= OBJC2_CLS_HIDDEN;
6829
6830 if (!CDecl->getSuperClass())
6831 // class is root
6832 flags |= CLS_ROOT;
6833 InstanceSize = "sizeof(struct _class_t)";
6834 InstanceStart = InstanceSize;
6835 Write__class_ro_t_initializer(Context, Result, flags,
6836 InstanceStart, InstanceSize,
6837 ClassMethods,
6838 0,
6839 0,
6840 0,
6841 "_OBJC_METACLASS_RO_$_",
6842 CDecl->getNameAsString());
6843
6844
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006845 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006846 flags = CLS;
6847 if (classIsHidden)
6848 flags |= OBJC2_CLS_HIDDEN;
6849
6850 if (hasObjCExceptionAttribute(*Context, CDecl))
6851 flags |= CLS_EXCEPTION;
6852
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006853 if (!CDecl->getSuperClass())
6854 // class is root
6855 flags |= CLS_ROOT;
6856
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006857 InstanceSize.clear();
6858 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006859 if (!ObjCSynthesizedStructs.count(CDecl)) {
6860 InstanceSize = "0";
6861 InstanceStart = "0";
6862 }
6863 else {
6864 InstanceSize = "sizeof(struct ";
6865 InstanceSize += CDecl->getNameAsString();
6866 InstanceSize += "_IMPL)";
6867
6868 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6869 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006870 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006871 }
6872 else
6873 InstanceStart = InstanceSize;
6874 }
6875 Write__class_ro_t_initializer(Context, Result, flags,
6876 InstanceStart, InstanceSize,
6877 InstanceMethods,
6878 RefedProtocols,
6879 IVars,
6880 ClassProperties,
6881 "_OBJC_CLASS_RO_$_",
6882 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006883
6884 Write_class_t(Context, Result,
6885 "OBJC_METACLASS_$_",
6886 CDecl, /*metaclass*/true);
6887
6888 Write_class_t(Context, Result,
6889 "OBJC_CLASS_$_",
6890 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006891
6892 if (ImplementationIsNonLazy(IDecl))
6893 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006895}
6896
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006897void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6898 int ClsDefCount = ClassImplementation.size();
6899 if (!ClsDefCount)
6900 return;
6901 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6902 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6903 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6904 for (int i = 0; i < ClsDefCount; i++) {
6905 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6906 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6907 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6908 Result += CDecl->getName(); Result += ",\n";
6909 }
6910 Result += "};\n";
6911}
6912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006913void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6914 int ClsDefCount = ClassImplementation.size();
6915 int CatDefCount = CategoryImplementation.size();
6916
6917 // For each implemented class, write out all its meta data.
6918 for (int i = 0; i < ClsDefCount; i++)
6919 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6920
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006921 RewriteClassSetupInitHook(Result);
6922
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006923 // For each implemented category, write out all its meta data.
6924 for (int i = 0; i < CatDefCount; i++)
6925 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6926
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006927 RewriteCategorySetupInitHook(Result);
6928
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006929 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006930 if (LangOpts.MicrosoftExt)
6931 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006932 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6933 Result += llvm::utostr(ClsDefCount); Result += "]";
6934 Result +=
6935 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6936 "regular,no_dead_strip\")))= {\n";
6937 for (int i = 0; i < ClsDefCount; i++) {
6938 Result += "\t&OBJC_CLASS_$_";
6939 Result += ClassImplementation[i]->getNameAsString();
6940 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006941 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006942 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006943
6944 if (!DefinedNonLazyClasses.empty()) {
6945 if (LangOpts.MicrosoftExt)
6946 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6947 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6948 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6949 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6950 Result += ",\n";
6951 }
6952 Result += "};\n";
6953 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006954 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006955
6956 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006957 if (LangOpts.MicrosoftExt)
6958 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006959 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6960 Result += llvm::utostr(CatDefCount); Result += "]";
6961 Result +=
6962 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6963 "regular,no_dead_strip\")))= {\n";
6964 for (int i = 0; i < CatDefCount; i++) {
6965 Result += "\t&_OBJC_$_CATEGORY_";
6966 Result +=
6967 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6968 Result += "_$_";
6969 Result += CategoryImplementation[i]->getNameAsString();
6970 Result += ",\n";
6971 }
6972 Result += "};\n";
6973 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006974
6975 if (!DefinedNonLazyCategories.empty()) {
6976 if (LangOpts.MicrosoftExt)
6977 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6978 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6979 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6980 Result += "\t&_OBJC_$_CATEGORY_";
6981 Result +=
6982 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6983 Result += "_$_";
6984 Result += DefinedNonLazyCategories[i]->getNameAsString();
6985 Result += ",\n";
6986 }
6987 Result += "};\n";
6988 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006989}
6990
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006991void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6992 if (LangOpts.MicrosoftExt)
6993 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6994
6995 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6996 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006997 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006998}
6999
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007000/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7001/// implementation.
7002void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7003 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007004 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007005 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7006 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007007 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007008 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7009 CDecl = CDecl->getNextClassCategory())
7010 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7011 break;
7012
7013 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007014 FullCategoryName += "_$_";
7015 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007016
7017 // Build _objc_method_list for class's instance methods if needed
7018 SmallVector<ObjCMethodDecl *, 32>
7019 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7020
7021 // If any of our property implementations have associated getters or
7022 // setters, produce metadata for them as well.
7023 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7024 PropEnd = IDecl->propimpl_end();
7025 Prop != PropEnd; ++Prop) {
7026 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7027 continue;
7028 if (!(*Prop)->getPropertyIvarDecl())
7029 continue;
7030 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7031 if (!PD)
7032 continue;
7033 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7034 InstanceMethods.push_back(Getter);
7035 if (PD->isReadOnly())
7036 continue;
7037 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7038 InstanceMethods.push_back(Setter);
7039 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007040
Fariborz Jahanian61186122012-02-17 18:40:41 +00007041 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7042 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7043 FullCategoryName, true);
7044
7045 SmallVector<ObjCMethodDecl *, 32>
7046 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7047
7048 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7049 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7050 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007051
7052 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007053 // Protocol's super protocol list
7054 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007055 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7056 E = CDecl->protocol_end();
7057
7058 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007059 RefedProtocols.push_back(*I);
7060 // Must write out all protocol definitions in current qualifier list,
7061 // and in their nested qualifiers before writing out current definition.
7062 RewriteObjCProtocolMetaData(*I, Result);
7063 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007064
Fariborz Jahanian61186122012-02-17 18:40:41 +00007065 Write_protocol_list_initializer(Context, Result,
7066 RefedProtocols,
7067 "_OBJC_CATEGORY_PROTOCOLS_$_",
7068 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007069
Fariborz Jahanian61186122012-02-17 18:40:41 +00007070 // Protocol's property metadata.
7071 std::vector<ObjCPropertyDecl *> ClassProperties;
7072 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7073 E = CDecl->prop_end(); I != E; ++I)
7074 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007075
Fariborz Jahanian61186122012-02-17 18:40:41 +00007076 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7077 /* Container */0,
7078 "_OBJC_$_PROP_LIST_",
7079 FullCategoryName);
7080
7081 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007082 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007083 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007084 InstanceMethods,
7085 ClassMethods,
7086 RefedProtocols,
7087 ClassProperties);
7088
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007089 // Determine if this category is also "non-lazy".
7090 if (ImplementationIsNonLazy(IDecl))
7091 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007092
7093}
7094
7095void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7096 int CatDefCount = CategoryImplementation.size();
7097 if (!CatDefCount)
7098 return;
7099 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7100 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7101 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7102 for (int i = 0; i < CatDefCount; i++) {
7103 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7104 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7105 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7106 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7107 Result += ClassDecl->getName();
7108 Result += "_$_";
7109 Result += CatDecl->getName();
7110 Result += ",\n";
7111 }
7112 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007113}
7114
7115// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7116/// class methods.
7117template<typename MethodIterator>
7118void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7119 MethodIterator MethodEnd,
7120 bool IsInstanceMethod,
7121 StringRef prefix,
7122 StringRef ClassName,
7123 std::string &Result) {
7124 if (MethodBegin == MethodEnd) return;
7125
7126 if (!objc_impl_method) {
7127 /* struct _objc_method {
7128 SEL _cmd;
7129 char *method_types;
7130 void *_imp;
7131 }
7132 */
7133 Result += "\nstruct _objc_method {\n";
7134 Result += "\tSEL _cmd;\n";
7135 Result += "\tchar *method_types;\n";
7136 Result += "\tvoid *_imp;\n";
7137 Result += "};\n";
7138
7139 objc_impl_method = true;
7140 }
7141
7142 // Build _objc_method_list for class's methods if needed
7143
7144 /* struct {
7145 struct _objc_method_list *next_method;
7146 int method_count;
7147 struct _objc_method method_list[];
7148 }
7149 */
7150 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007151 Result += "\n";
7152 if (LangOpts.MicrosoftExt) {
7153 if (IsInstanceMethod)
7154 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7155 else
7156 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7157 }
7158 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007159 Result += "\tstruct _objc_method_list *next_method;\n";
7160 Result += "\tint method_count;\n";
7161 Result += "\tstruct _objc_method method_list[";
7162 Result += utostr(NumMethods);
7163 Result += "];\n} _OBJC_";
7164 Result += prefix;
7165 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7166 Result += "_METHODS_";
7167 Result += ClassName;
7168 Result += " __attribute__ ((used, section (\"__OBJC, __";
7169 Result += IsInstanceMethod ? "inst" : "cls";
7170 Result += "_meth\")))= ";
7171 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7172
7173 Result += "\t,{{(SEL)\"";
7174 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7175 std::string MethodTypeString;
7176 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7177 Result += "\", \"";
7178 Result += MethodTypeString;
7179 Result += "\", (void *)";
7180 Result += MethodInternalNames[*MethodBegin];
7181 Result += "}\n";
7182 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7183 Result += "\t ,{(SEL)\"";
7184 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7185 std::string MethodTypeString;
7186 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7187 Result += "\", \"";
7188 Result += MethodTypeString;
7189 Result += "\", (void *)";
7190 Result += MethodInternalNames[*MethodBegin];
7191 Result += "}\n";
7192 }
7193 Result += "\t }\n};\n";
7194}
7195
7196Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7197 SourceRange OldRange = IV->getSourceRange();
7198 Expr *BaseExpr = IV->getBase();
7199
7200 // Rewrite the base, but without actually doing replaces.
7201 {
7202 DisableReplaceStmtScope S(*this);
7203 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7204 IV->setBase(BaseExpr);
7205 }
7206
7207 ObjCIvarDecl *D = IV->getDecl();
7208
7209 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007210
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007211 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7212 const ObjCInterfaceType *iFaceDecl =
7213 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7214 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7215 // lookup which class implements the instance variable.
7216 ObjCInterfaceDecl *clsDeclared = 0;
7217 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7218 clsDeclared);
7219 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7220
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007221 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007222 std::string IvarOffsetName;
7223 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7224
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007225 ReferencedIvars[clsDeclared].insert(D);
7226
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007227 // cast offset to "char *".
7228 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7229 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007230 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007231 BaseExpr);
7232 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7233 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7234 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007235 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7236 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007237 SourceLocation());
7238 BinaryOperator *addExpr =
7239 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7240 Context->getPointerType(Context->CharTy),
7241 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007242 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007243 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7244 SourceLocation(),
7245 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007246 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007247 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007248 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007249
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007250 castExpr = NoTypeInfoCStyleCastExpr(Context,
7251 castT,
7252 CK_BitCast,
7253 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007254 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007255 VK_LValue, OK_Ordinary,
7256 SourceLocation());
7257 PE = new (Context) ParenExpr(OldRange.getBegin(),
7258 OldRange.getEnd(),
7259 Exp);
7260
7261 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007262 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007263
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007264 ReplaceStmtWithRange(IV, Replacement, OldRange);
7265 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007266}