blob: ab5a476510093789acbd25a525d990a5fcd01c85 [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;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000111 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000113 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
114 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
115
116 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
117 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000119 SmallVector<Stmt *, 32> Stmts;
120 SmallVector<int, 8> ObjCBcLabelNo;
121 // Remember all the @protocol(<expr>) expressions.
122 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
123
124 llvm::DenseSet<uint64_t> CopyDestroyCache;
125
126 // Block expressions.
127 SmallVector<BlockExpr *, 32> Blocks;
128 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000129 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000130
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
133 // Block related declarations.
134 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
135 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
136 SmallVector<ValueDecl *, 8> BlockByRefDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
138 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
139 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
140 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
141
142 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000143 llvm::DenseMap<ObjCInterfaceDecl *,
144 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000146 // This maps an original source AST to it's rewritten form. This allows
147 // us to avoid rewriting the same node twice (which is very uncommon).
148 // This is needed to support some of the exotic property rewriting.
149 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
150
151 // Needed for header files being rewritten
152 bool IsHeader;
153 bool SilenceRewriteMacroWarning;
154 bool objc_impl_method;
155
156 bool DisableReplaceStmt;
157 class DisableReplaceStmtScope {
158 RewriteModernObjC &R;
159 bool SavedValue;
160
161 public:
162 DisableReplaceStmtScope(RewriteModernObjC &R)
163 : R(R), SavedValue(R.DisableReplaceStmt) {
164 R.DisableReplaceStmt = true;
165 }
166 ~DisableReplaceStmtScope() {
167 R.DisableReplaceStmt = SavedValue;
168 }
169 };
170 void InitializeCommon(ASTContext &context);
171
172 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000173 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000174 // Top Level Driver code.
175 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
176 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
177 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
178 if (!Class->isThisDeclarationADefinition()) {
179 RewriteForwardClassDecl(D);
180 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000181 } else {
182 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000183 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000185 }
186 }
187
188 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
189 if (!Proto->isThisDeclarationADefinition()) {
190 RewriteForwardProtocolDecl(D);
191 break;
192 }
193 }
194
195 HandleTopLevelSingleDecl(*I);
196 }
197 return true;
198 }
199 void HandleTopLevelSingleDecl(Decl *D);
200 void HandleDeclInMainFile(Decl *D);
201 RewriteModernObjC(std::string inFile, raw_ostream *OS,
202 DiagnosticsEngine &D, const LangOptions &LOpts,
203 bool silenceMacroWarn);
204
205 ~RewriteModernObjC() {}
206
207 virtual void HandleTranslationUnit(ASTContext &C);
208
209 void ReplaceStmt(Stmt *Old, Stmt *New) {
210 Stmt *ReplacingStmt = ReplacedNodes[Old];
211
212 if (ReplacingStmt)
213 return; // We can't rewrite the same node twice.
214
215 if (DisableReplaceStmt)
216 return;
217
218 // If replacement succeeded or warning disabled return with no warning.
219 if (!Rewrite.ReplaceStmt(Old, New)) {
220 ReplacedNodes[Old] = New;
221 return;
222 }
223 if (SilenceRewriteMacroWarning)
224 return;
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 }
228
229 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
230 if (DisableReplaceStmt)
231 return;
232
233 // Measure the old text.
234 int Size = Rewrite.getRangeSize(SrcRange);
235 if (Size == -1) {
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 return;
239 }
240 // Get the new text.
241 std::string SStr;
242 llvm::raw_string_ostream S(SStr);
243 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
244 const std::string &Str = S.str();
245
246 // If replacement succeeded or warning disabled return with no warning.
247 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
248 ReplacedNodes[Old] = New;
249 return;
250 }
251 if (SilenceRewriteMacroWarning)
252 return;
253 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
254 << Old->getSourceRange();
255 }
256
257 void InsertText(SourceLocation Loc, StringRef Str,
258 bool InsertAfter = true) {
259 // If insertion succeeded or warning disabled return with no warning.
260 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
261 SilenceRewriteMacroWarning)
262 return;
263
264 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
265 }
266
267 void ReplaceText(SourceLocation Start, unsigned OrigLength,
268 StringRef Str) {
269 // If removal succeeded or warning disabled return with no warning.
270 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
271 SilenceRewriteMacroWarning)
272 return;
273
274 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
275 }
276
277 // Syntactic Rewriting.
278 void RewriteRecordBody(RecordDecl *RD);
279 void RewriteInclude();
280 void RewriteForwardClassDecl(DeclGroupRef D);
281 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
282 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
283 const std::string &typedefString);
284 void RewriteImplementations();
285 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
286 ObjCImplementationDecl *IMD,
287 ObjCCategoryImplDecl *CID);
288 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
289 void RewriteImplementationDecl(Decl *Dcl);
290 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
291 ObjCMethodDecl *MDecl, std::string &ResultStr);
292 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
293 const FunctionType *&FPRetType);
294 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
295 ValueDecl *VD, bool def=false);
296 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
297 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
298 void RewriteForwardProtocolDecl(DeclGroupRef D);
299 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
300 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
301 void RewriteProperty(ObjCPropertyDecl *prop);
302 void RewriteFunctionDecl(FunctionDecl *FD);
303 void RewriteBlockPointerType(std::string& Str, QualType Type);
304 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
305 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
306 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
307 void RewriteTypeOfDecl(VarDecl *VD);
308 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
309
310 // Expression Rewriting.
311 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
312 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
313 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
314 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
316 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
317 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
318 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
319 void RewriteTryReturnStmts(Stmt *S);
320 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
321 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
322 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
323 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
324 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
325 SourceLocation OrigEnd);
326 Stmt *RewriteBreakStmt(BreakStmt *S);
327 Stmt *RewriteContinueStmt(ContinueStmt *S);
328 void RewriteCastExpr(CStyleCastExpr *CE);
329
330 // Block rewriting.
331 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
332
333 // Block specific rewrite rules.
334 void RewriteBlockPointerDecl(NamedDecl *VD);
335 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000336 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
338 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
339
340 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
341 std::string &Result);
342
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000343 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
344
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000345 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
346
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000347 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
348 std::string &Result);
349
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350 virtual void Initialize(ASTContext &context);
351
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
358
359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 // Rewriting metadata
376 template<typename MethodIterator>
377 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
378 MethodIterator MethodEnd,
379 bool IsInstanceMethod,
380 StringRef prefix,
381 StringRef ClassName,
382 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000383 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
384 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000385 virtual void RewriteObjCProtocolListMetaData(
386 const ObjCList<ObjCProtocolDecl> &Prots,
387 StringRef prefix, StringRef ClassName, std::string &Result);
388 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
389 std::string &Result);
390 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000391 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000392 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
393 std::string &Result);
394
395 // Rewriting ivar
396 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
397 std::string &Result);
398 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
399
400
401 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
402 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
403 StringRef funcName, std::string Tag);
404 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
405 StringRef funcName, std::string Tag);
406 std::string SynthesizeBlockImpl(BlockExpr *CE,
407 std::string Tag, std::string Desc);
408 std::string SynthesizeBlockDescriptor(std::string DescTag,
409 std::string ImplTag,
410 int i, StringRef funcName,
411 unsigned hasCopy);
412 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
413 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
414 StringRef FunName);
415 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
416 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000417 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418
419 // Misc. helper routines.
420 QualType getProtocolType();
421 void WarnAboutReturnGotoStmts(Stmt *S);
422 void HasReturnStmts(Stmt *S, bool &hasReturns);
423 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
424 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
425 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
426
427 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
428 void CollectBlockDeclRefInfo(BlockExpr *Exp);
429 void GetBlockDeclRefExprs(Stmt *S);
430 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000431 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000432 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
433
434 // We avoid calling Type::isBlockPointerType(), since it operates on the
435 // canonical type. We only care if the top-level type is a closure pointer.
436 bool isTopLevelBlockPointerType(QualType T) {
437 return isa<BlockPointerType>(T);
438 }
439
440 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
441 /// to a function pointer type and upon success, returns true; false
442 /// otherwise.
443 bool convertBlockPointerToFunctionPointer(QualType &T) {
444 if (isTopLevelBlockPointerType(T)) {
445 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
446 T = Context->getPointerType(BPT->getPointeeType());
447 return true;
448 }
449 return false;
450 }
451
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000452 bool convertObjCTypeToCStyleType(QualType &T);
453
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 bool needToScanForQualifiers(QualType T);
455 QualType getSuperStructType();
456 QualType getConstantStringStructType();
457 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
458 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
459
460 void convertToUnqualifiedObjCType(QualType &T) {
461 if (T->isObjCQualifiedIdType())
462 T = Context->getObjCIdType();
463 else if (T->isObjCQualifiedClassType())
464 T = Context->getObjCClassType();
465 else if (T->isObjCObjectPointerType() &&
466 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
467 if (const ObjCObjectPointerType * OBJPT =
468 T->getAsObjCInterfacePointerType()) {
469 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
470 T = QualType(IFaceT, 0);
471 T = Context->getPointerType(T);
472 }
473 }
474 }
475
476 // FIXME: This predicate seems like it would be useful to add to ASTContext.
477 bool isObjCType(QualType T) {
478 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
479 return false;
480
481 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
482
483 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
484 OCT == Context->getCanonicalType(Context->getObjCClassType()))
485 return true;
486
487 if (const PointerType *PT = OCT->getAs<PointerType>()) {
488 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
489 PT->getPointeeType()->isObjCQualifiedIdType())
490 return true;
491 }
492 return false;
493 }
494 bool PointerTypeTakesAnyBlockArguments(QualType QT);
495 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
496 void GetExtentOfArgList(const char *Name, const char *&LParen,
497 const char *&RParen);
498
499 void QuoteDoublequotes(std::string &From, std::string &To) {
500 for (unsigned i = 0; i < From.length(); i++) {
501 if (From[i] == '"')
502 To += "\\\"";
503 else
504 To += From[i];
505 }
506 }
507
508 QualType getSimpleFunctionType(QualType result,
509 const QualType *args,
510 unsigned numArgs,
511 bool variadic = false) {
512 if (result == Context->getObjCInstanceType())
513 result = Context->getObjCIdType();
514 FunctionProtoType::ExtProtoInfo fpi;
515 fpi.Variadic = variadic;
516 return Context->getFunctionType(result, args, numArgs, fpi);
517 }
518
519 // Helper function: create a CStyleCastExpr with trivial type source info.
520 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
521 CastKind Kind, Expr *E) {
522 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
523 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
524 SourceLocation(), SourceLocation());
525 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000526
527 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
528 IdentifierInfo* II = &Context->Idents.get("load");
529 Selector LoadSel = Context->Selectors.getSelector(0, &II);
530 return OD->getClassMethod(LoadSel) != 0;
531 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000532 };
533
534}
535
536void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
537 NamedDecl *D) {
538 if (const FunctionProtoType *fproto
539 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
540 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
541 E = fproto->arg_type_end(); I && (I != E); ++I)
542 if (isTopLevelBlockPointerType(*I)) {
543 // All the args are checked/rewritten. Don't call twice!
544 RewriteBlockPointerDecl(D);
545 break;
546 }
547 }
548}
549
550void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
551 const PointerType *PT = funcType->getAs<PointerType>();
552 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
553 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
554}
555
556static bool IsHeaderFile(const std::string &Filename) {
557 std::string::size_type DotPos = Filename.rfind('.');
558
559 if (DotPos == std::string::npos) {
560 // no file extension
561 return false;
562 }
563
564 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
565 // C header: .h
566 // C++ header: .hh or .H;
567 return Ext == "h" || Ext == "hh" || Ext == "H";
568}
569
570RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
571 DiagnosticsEngine &D, const LangOptions &LOpts,
572 bool silenceMacroWarn)
573 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
574 SilenceRewriteMacroWarning(silenceMacroWarn) {
575 IsHeader = IsHeaderFile(inFile);
576 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
577 "rewriting sub-expression within a macro (may not be correct)");
578 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
579 DiagnosticsEngine::Warning,
580 "rewriter doesn't support user-specified control flow semantics "
581 "for @try/@finally (code may not execute properly)");
582}
583
584ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
585 raw_ostream* OS,
586 DiagnosticsEngine &Diags,
587 const LangOptions &LOpts,
588 bool SilenceRewriteMacroWarning) {
589 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
590}
591
592void RewriteModernObjC::InitializeCommon(ASTContext &context) {
593 Context = &context;
594 SM = &Context->getSourceManager();
595 TUDecl = Context->getTranslationUnitDecl();
596 MsgSendFunctionDecl = 0;
597 MsgSendSuperFunctionDecl = 0;
598 MsgSendStretFunctionDecl = 0;
599 MsgSendSuperStretFunctionDecl = 0;
600 MsgSendFpretFunctionDecl = 0;
601 GetClassFunctionDecl = 0;
602 GetMetaClassFunctionDecl = 0;
603 GetSuperClassFunctionDecl = 0;
604 SelGetUidFunctionDecl = 0;
605 CFStringFunctionDecl = 0;
606 ConstantStringClassReference = 0;
607 NSStringRecord = 0;
608 CurMethodDef = 0;
609 CurFunctionDef = 0;
610 CurFunctionDeclToDeclareForBlock = 0;
611 GlobalVarDecl = 0;
612 SuperStructDecl = 0;
613 ProtocolTypeDecl = 0;
614 ConstantStringDecl = 0;
615 BcLabelCount = 0;
616 SuperContructorFunctionDecl = 0;
617 NumObjCStringLiterals = 0;
618 PropParentMap = 0;
619 CurrentBody = 0;
620 DisableReplaceStmt = false;
621 objc_impl_method = false;
622
623 // Get the ID and start/end of the main file.
624 MainFileID = SM->getMainFileID();
625 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
626 MainFileStart = MainBuf->getBufferStart();
627 MainFileEnd = MainBuf->getBufferEnd();
628
David Blaikie4e4d0842012-03-11 07:00:24 +0000629 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000630}
631
632//===----------------------------------------------------------------------===//
633// Top Level Driver Code
634//===----------------------------------------------------------------------===//
635
636void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
637 if (Diags.hasErrorOccurred())
638 return;
639
640 // Two cases: either the decl could be in the main file, or it could be in a
641 // #included file. If the former, rewrite it now. If the later, check to see
642 // if we rewrote the #include/#import.
643 SourceLocation Loc = D->getLocation();
644 Loc = SM->getExpansionLoc(Loc);
645
646 // If this is for a builtin, ignore it.
647 if (Loc.isInvalid()) return;
648
649 // Look for built-in declarations that we need to refer during the rewrite.
650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
651 RewriteFunctionDecl(FD);
652 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
653 // declared in <Foundation/NSString.h>
654 if (FVD->getName() == "_NSConstantStringClassReference") {
655 ConstantStringClassReference = FVD;
656 return;
657 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000658 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
659 RewriteCategoryDecl(CD);
660 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
661 if (PD->isThisDeclarationADefinition())
662 RewriteProtocolDecl(PD);
663 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
664 // Recurse into linkage specifications
665 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
666 DIEnd = LSD->decls_end();
667 DI != DIEnd; ) {
668 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
669 if (!IFace->isThisDeclarationADefinition()) {
670 SmallVector<Decl *, 8> DG;
671 SourceLocation StartLoc = IFace->getLocStart();
672 do {
673 if (isa<ObjCInterfaceDecl>(*DI) &&
674 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
675 StartLoc == (*DI)->getLocStart())
676 DG.push_back(*DI);
677 else
678 break;
679
680 ++DI;
681 } while (DI != DIEnd);
682 RewriteForwardClassDecl(DG);
683 continue;
684 }
685 }
686
687 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
688 if (!Proto->isThisDeclarationADefinition()) {
689 SmallVector<Decl *, 8> DG;
690 SourceLocation StartLoc = Proto->getLocStart();
691 do {
692 if (isa<ObjCProtocolDecl>(*DI) &&
693 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
694 StartLoc == (*DI)->getLocStart())
695 DG.push_back(*DI);
696 else
697 break;
698
699 ++DI;
700 } while (DI != DIEnd);
701 RewriteForwardProtocolDecl(DG);
702 continue;
703 }
704 }
705
706 HandleTopLevelSingleDecl(*DI);
707 ++DI;
708 }
709 }
710 // If we have a decl in the main file, see if we should rewrite it.
711 if (SM->isFromMainFile(Loc))
712 return HandleDeclInMainFile(D);
713}
714
715//===----------------------------------------------------------------------===//
716// Syntactic (non-AST) Rewriting Code
717//===----------------------------------------------------------------------===//
718
719void RewriteModernObjC::RewriteInclude() {
720 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
721 StringRef MainBuf = SM->getBufferData(MainFileID);
722 const char *MainBufStart = MainBuf.begin();
723 const char *MainBufEnd = MainBuf.end();
724 size_t ImportLen = strlen("import");
725
726 // Loop over the whole file, looking for includes.
727 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
728 if (*BufPtr == '#') {
729 if (++BufPtr == MainBufEnd)
730 return;
731 while (*BufPtr == ' ' || *BufPtr == '\t')
732 if (++BufPtr == MainBufEnd)
733 return;
734 if (!strncmp(BufPtr, "import", ImportLen)) {
735 // replace import with include
736 SourceLocation ImportLoc =
737 LocStart.getLocWithOffset(BufPtr-MainBufStart);
738 ReplaceText(ImportLoc, ImportLen, "include");
739 BufPtr += ImportLen;
740 }
741 }
742 }
743}
744
745static std::string getIvarAccessString(ObjCIvarDecl *OID) {
746 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
747 std::string S;
748 S = "((struct ";
749 S += ClassDecl->getIdentifier()->getName();
750 S += "_IMPL *)self)->";
751 S += OID->getName();
752 return S;
753}
754
755void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
756 ObjCImplementationDecl *IMD,
757 ObjCCategoryImplDecl *CID) {
758 static bool objcGetPropertyDefined = false;
759 static bool objcSetPropertyDefined = false;
760 SourceLocation startLoc = PID->getLocStart();
761 InsertText(startLoc, "// ");
762 const char *startBuf = SM->getCharacterData(startLoc);
763 assert((*startBuf == '@') && "bogus @synthesize location");
764 const char *semiBuf = strchr(startBuf, ';');
765 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
766 SourceLocation onePastSemiLoc =
767 startLoc.getLocWithOffset(semiBuf-startBuf+1);
768
769 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
770 return; // FIXME: is this correct?
771
772 // Generate the 'getter' function.
773 ObjCPropertyDecl *PD = PID->getPropertyDecl();
774 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
775
776 if (!OID)
777 return;
778 unsigned Attributes = PD->getPropertyAttributes();
779 if (!PD->getGetterMethodDecl()->isDefined()) {
780 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
781 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
782 ObjCPropertyDecl::OBJC_PR_copy));
783 std::string Getr;
784 if (GenGetProperty && !objcGetPropertyDefined) {
785 objcGetPropertyDefined = true;
786 // FIXME. Is this attribute correct in all cases?
787 Getr = "\nextern \"C\" __declspec(dllimport) "
788 "id objc_getProperty(id, SEL, long, bool);\n";
789 }
790 RewriteObjCMethodDecl(OID->getContainingInterface(),
791 PD->getGetterMethodDecl(), Getr);
792 Getr += "{ ";
793 // Synthesize an explicit cast to gain access to the ivar.
794 // See objc-act.c:objc_synthesize_new_getter() for details.
795 if (GenGetProperty) {
796 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
797 Getr += "typedef ";
798 const FunctionType *FPRetType = 0;
799 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
800 FPRetType);
801 Getr += " _TYPE";
802 if (FPRetType) {
803 Getr += ")"; // close the precedence "scope" for "*".
804
805 // Now, emit the argument types (if any).
806 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
807 Getr += "(";
808 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
809 if (i) Getr += ", ";
810 std::string ParamStr = FT->getArgType(i).getAsString(
811 Context->getPrintingPolicy());
812 Getr += ParamStr;
813 }
814 if (FT->isVariadic()) {
815 if (FT->getNumArgs()) Getr += ", ";
816 Getr += "...";
817 }
818 Getr += ")";
819 } else
820 Getr += "()";
821 }
822 Getr += ";\n";
823 Getr += "return (_TYPE)";
824 Getr += "objc_getProperty(self, _cmd, ";
825 RewriteIvarOffsetComputation(OID, Getr);
826 Getr += ", 1)";
827 }
828 else
829 Getr += "return " + getIvarAccessString(OID);
830 Getr += "; }";
831 InsertText(onePastSemiLoc, Getr);
832 }
833
834 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
835 return;
836
837 // Generate the 'setter' function.
838 std::string Setr;
839 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
840 ObjCPropertyDecl::OBJC_PR_copy);
841 if (GenSetProperty && !objcSetPropertyDefined) {
842 objcSetPropertyDefined = true;
843 // FIXME. Is this attribute correct in all cases?
844 Setr = "\nextern \"C\" __declspec(dllimport) "
845 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
846 }
847
848 RewriteObjCMethodDecl(OID->getContainingInterface(),
849 PD->getSetterMethodDecl(), Setr);
850 Setr += "{ ";
851 // Synthesize an explicit cast to initialize the ivar.
852 // See objc-act.c:objc_synthesize_new_setter() for details.
853 if (GenSetProperty) {
854 Setr += "objc_setProperty (self, _cmd, ";
855 RewriteIvarOffsetComputation(OID, Setr);
856 Setr += ", (id)";
857 Setr += PD->getName();
858 Setr += ", ";
859 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
860 Setr += "0, ";
861 else
862 Setr += "1, ";
863 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
864 Setr += "1)";
865 else
866 Setr += "0)";
867 }
868 else {
869 Setr += getIvarAccessString(OID) + " = ";
870 Setr += PD->getName();
871 }
872 Setr += "; }";
873 InsertText(onePastSemiLoc, Setr);
874}
875
876static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
877 std::string &typedefString) {
878 typedefString += "#ifndef _REWRITER_typedef_";
879 typedefString += ForwardDecl->getNameAsString();
880 typedefString += "\n";
881 typedefString += "#define _REWRITER_typedef_";
882 typedefString += ForwardDecl->getNameAsString();
883 typedefString += "\n";
884 typedefString += "typedef struct objc_object ";
885 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000886 // typedef struct { } _objc_exc_Classname;
887 typedefString += ";\ntypedef struct {} _objc_exc_";
888 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000889 typedefString += ";\n#endif\n";
890}
891
892void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
893 const std::string &typedefString) {
894 SourceLocation startLoc = ClassDecl->getLocStart();
895 const char *startBuf = SM->getCharacterData(startLoc);
896 const char *semiPtr = strchr(startBuf, ';');
897 // Replace the @class with typedefs corresponding to the classes.
898 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
899}
900
901void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
902 std::string typedefString;
903 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
905 if (I == D.begin()) {
906 // Translate to typedef's that forward reference structs with the same name
907 // as the class. As a convenience, we include the original declaration
908 // as a comment.
909 typedefString += "// @class ";
910 typedefString += ForwardDecl->getNameAsString();
911 typedefString += ";\n";
912 }
913 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
914 }
915 DeclGroupRef::iterator I = D.begin();
916 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
917}
918
919void RewriteModernObjC::RewriteForwardClassDecl(
920 const llvm::SmallVector<Decl*, 8> &D) {
921 std::string typedefString;
922 for (unsigned i = 0; i < D.size(); i++) {
923 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
924 if (i == 0) {
925 typedefString += "// @class ";
926 typedefString += ForwardDecl->getNameAsString();
927 typedefString += ";\n";
928 }
929 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
930 }
931 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
932}
933
934void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
935 // When method is a synthesized one, such as a getter/setter there is
936 // nothing to rewrite.
937 if (Method->isImplicit())
938 return;
939 SourceLocation LocStart = Method->getLocStart();
940 SourceLocation LocEnd = Method->getLocEnd();
941
942 if (SM->getExpansionLineNumber(LocEnd) >
943 SM->getExpansionLineNumber(LocStart)) {
944 InsertText(LocStart, "#if 0\n");
945 ReplaceText(LocEnd, 1, ";\n#endif\n");
946 } else {
947 InsertText(LocStart, "// ");
948 }
949}
950
951void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
952 SourceLocation Loc = prop->getAtLoc();
953
954 ReplaceText(Loc, 0, "// ");
955 // FIXME: handle properties that are declared across multiple lines.
956}
957
958void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
959 SourceLocation LocStart = CatDecl->getLocStart();
960
961 // FIXME: handle category headers that are declared across multiple lines.
962 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000963 if (CatDecl->getIvarLBraceLoc().isValid())
964 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000965 for (ObjCCategoryDecl::ivar_iterator
966 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
967 ObjCIvarDecl *Ivar = (*I);
968 SourceLocation LocStart = Ivar->getLocStart();
969 ReplaceText(LocStart, 0, "// ");
970 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000971 if (CatDecl->getIvarRBraceLoc().isValid())
972 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
973
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000974 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
975 E = CatDecl->prop_end(); I != E; ++I)
976 RewriteProperty(*I);
977
978 for (ObjCCategoryDecl::instmeth_iterator
979 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
980 I != E; ++I)
981 RewriteMethodDeclaration(*I);
982 for (ObjCCategoryDecl::classmeth_iterator
983 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
984 I != E; ++I)
985 RewriteMethodDeclaration(*I);
986
987 // Lastly, comment out the @end.
988 ReplaceText(CatDecl->getAtEndRange().getBegin(),
989 strlen("@end"), "/* @end */");
990}
991
992void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
993 SourceLocation LocStart = PDecl->getLocStart();
994 assert(PDecl->isThisDeclarationADefinition());
995
996 // FIXME: handle protocol headers that are declared across multiple lines.
997 ReplaceText(LocStart, 0, "// ");
998
999 for (ObjCProtocolDecl::instmeth_iterator
1000 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1001 I != E; ++I)
1002 RewriteMethodDeclaration(*I);
1003 for (ObjCProtocolDecl::classmeth_iterator
1004 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1005 I != E; ++I)
1006 RewriteMethodDeclaration(*I);
1007
1008 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1009 E = PDecl->prop_end(); I != E; ++I)
1010 RewriteProperty(*I);
1011
1012 // Lastly, comment out the @end.
1013 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1014 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1015
1016 // Must comment out @optional/@required
1017 const char *startBuf = SM->getCharacterData(LocStart);
1018 const char *endBuf = SM->getCharacterData(LocEnd);
1019 for (const char *p = startBuf; p < endBuf; p++) {
1020 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1021 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1022 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1023
1024 }
1025 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1026 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1027 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1028
1029 }
1030 }
1031}
1032
1033void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1034 SourceLocation LocStart = (*D.begin())->getLocStart();
1035 if (LocStart.isInvalid())
1036 llvm_unreachable("Invalid SourceLocation");
1037 // FIXME: handle forward protocol that are declared across multiple lines.
1038 ReplaceText(LocStart, 0, "// ");
1039}
1040
1041void
1042RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1043 SourceLocation LocStart = DG[0]->getLocStart();
1044 if (LocStart.isInvalid())
1045 llvm_unreachable("Invalid SourceLocation");
1046 // FIXME: handle forward protocol that are declared across multiple lines.
1047 ReplaceText(LocStart, 0, "// ");
1048}
1049
1050void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1051 const FunctionType *&FPRetType) {
1052 if (T->isObjCQualifiedIdType())
1053 ResultStr += "id";
1054 else if (T->isFunctionPointerType() ||
1055 T->isBlockPointerType()) {
1056 // needs special handling, since pointer-to-functions have special
1057 // syntax (where a decaration models use).
1058 QualType retType = T;
1059 QualType PointeeTy;
1060 if (const PointerType* PT = retType->getAs<PointerType>())
1061 PointeeTy = PT->getPointeeType();
1062 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1063 PointeeTy = BPT->getPointeeType();
1064 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1065 ResultStr += FPRetType->getResultType().getAsString(
1066 Context->getPrintingPolicy());
1067 ResultStr += "(*";
1068 }
1069 } else
1070 ResultStr += T.getAsString(Context->getPrintingPolicy());
1071}
1072
1073void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1074 ObjCMethodDecl *OMD,
1075 std::string &ResultStr) {
1076 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1077 const FunctionType *FPRetType = 0;
1078 ResultStr += "\nstatic ";
1079 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1080 ResultStr += " ";
1081
1082 // Unique method name
1083 std::string NameStr;
1084
1085 if (OMD->isInstanceMethod())
1086 NameStr += "_I_";
1087 else
1088 NameStr += "_C_";
1089
1090 NameStr += IDecl->getNameAsString();
1091 NameStr += "_";
1092
1093 if (ObjCCategoryImplDecl *CID =
1094 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1095 NameStr += CID->getNameAsString();
1096 NameStr += "_";
1097 }
1098 // Append selector names, replacing ':' with '_'
1099 {
1100 std::string selString = OMD->getSelector().getAsString();
1101 int len = selString.size();
1102 for (int i = 0; i < len; i++)
1103 if (selString[i] == ':')
1104 selString[i] = '_';
1105 NameStr += selString;
1106 }
1107 // Remember this name for metadata emission
1108 MethodInternalNames[OMD] = NameStr;
1109 ResultStr += NameStr;
1110
1111 // Rewrite arguments
1112 ResultStr += "(";
1113
1114 // invisible arguments
1115 if (OMD->isInstanceMethod()) {
1116 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1117 selfTy = Context->getPointerType(selfTy);
1118 if (!LangOpts.MicrosoftExt) {
1119 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1120 ResultStr += "struct ";
1121 }
1122 // When rewriting for Microsoft, explicitly omit the structure name.
1123 ResultStr += IDecl->getNameAsString();
1124 ResultStr += " *";
1125 }
1126 else
1127 ResultStr += Context->getObjCClassType().getAsString(
1128 Context->getPrintingPolicy());
1129
1130 ResultStr += " self, ";
1131 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1132 ResultStr += " _cmd";
1133
1134 // Method arguments.
1135 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1136 E = OMD->param_end(); PI != E; ++PI) {
1137 ParmVarDecl *PDecl = *PI;
1138 ResultStr += ", ";
1139 if (PDecl->getType()->isObjCQualifiedIdType()) {
1140 ResultStr += "id ";
1141 ResultStr += PDecl->getNameAsString();
1142 } else {
1143 std::string Name = PDecl->getNameAsString();
1144 QualType QT = PDecl->getType();
1145 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1146 if (convertBlockPointerToFunctionPointer(QT))
1147 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1148 else
1149 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1150 ResultStr += Name;
1151 }
1152 }
1153 if (OMD->isVariadic())
1154 ResultStr += ", ...";
1155 ResultStr += ") ";
1156
1157 if (FPRetType) {
1158 ResultStr += ")"; // close the precedence "scope" for "*".
1159
1160 // Now, emit the argument types (if any).
1161 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1162 ResultStr += "(";
1163 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1164 if (i) ResultStr += ", ";
1165 std::string ParamStr = FT->getArgType(i).getAsString(
1166 Context->getPrintingPolicy());
1167 ResultStr += ParamStr;
1168 }
1169 if (FT->isVariadic()) {
1170 if (FT->getNumArgs()) ResultStr += ", ";
1171 ResultStr += "...";
1172 }
1173 ResultStr += ")";
1174 } else {
1175 ResultStr += "()";
1176 }
1177 }
1178}
1179void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1180 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1181 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1182
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001183 if (IMD) {
1184 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001185 if (IMD->getIvarLBraceLoc().isValid())
1186 InsertText(IMD->getIvarLBraceLoc(), "// ");
1187 for (ObjCImplementationDecl::ivar_iterator
1188 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1189 ObjCIvarDecl *Ivar = (*I);
1190 SourceLocation LocStart = Ivar->getLocStart();
1191 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001192 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001193 if (IMD->getIvarRBraceLoc().isValid())
1194 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001195 }
1196 else
1197 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001198
1199 for (ObjCCategoryImplDecl::instmeth_iterator
1200 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1201 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1202 I != E; ++I) {
1203 std::string ResultStr;
1204 ObjCMethodDecl *OMD = *I;
1205 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1206 SourceLocation LocStart = OMD->getLocStart();
1207 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1208
1209 const char *startBuf = SM->getCharacterData(LocStart);
1210 const char *endBuf = SM->getCharacterData(LocEnd);
1211 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1212 }
1213
1214 for (ObjCCategoryImplDecl::classmeth_iterator
1215 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1216 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1217 I != E; ++I) {
1218 std::string ResultStr;
1219 ObjCMethodDecl *OMD = *I;
1220 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1221 SourceLocation LocStart = OMD->getLocStart();
1222 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1223
1224 const char *startBuf = SM->getCharacterData(LocStart);
1225 const char *endBuf = SM->getCharacterData(LocEnd);
1226 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1227 }
1228 for (ObjCCategoryImplDecl::propimpl_iterator
1229 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1230 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1231 I != E; ++I) {
1232 RewritePropertyImplDecl(*I, IMD, CID);
1233 }
1234
1235 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1236}
1237
1238void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001239 // Do not synthesize more than once.
1240 if (ObjCSynthesizedStructs.count(ClassDecl))
1241 return;
1242 // Make sure super class's are written before current class is written.
1243 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1244 while (SuperClass) {
1245 RewriteInterfaceDecl(SuperClass);
1246 SuperClass = SuperClass->getSuperClass();
1247 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001248 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001249 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001250 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001251 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001252 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1253
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001254 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001255 // Mark this typedef as having been written into its c++ equivalent.
1256 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257
1258 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260 RewriteProperty(*I);
1261 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001262 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001263 I != E; ++I)
1264 RewriteMethodDeclaration(*I);
1265 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001266 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001267 I != E; ++I)
1268 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001269
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001270 // Lastly, comment out the @end.
1271 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1272 "/* @end */");
1273 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001274}
1275
1276Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1277 SourceRange OldRange = PseudoOp->getSourceRange();
1278
1279 // We just magically know some things about the structure of this
1280 // expression.
1281 ObjCMessageExpr *OldMsg =
1282 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1283 PseudoOp->getNumSemanticExprs() - 1));
1284
1285 // Because the rewriter doesn't allow us to rewrite rewritten code,
1286 // we need to suppress rewriting the sub-statements.
1287 Expr *Base, *RHS;
1288 {
1289 DisableReplaceStmtScope S(*this);
1290
1291 // Rebuild the base expression if we have one.
1292 Base = 0;
1293 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1294 Base = OldMsg->getInstanceReceiver();
1295 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1296 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1297 }
1298
1299 // Rebuild the RHS.
1300 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1301 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1302 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1303 }
1304
1305 // TODO: avoid this copy.
1306 SmallVector<SourceLocation, 1> SelLocs;
1307 OldMsg->getSelectorLocs(SelLocs);
1308
1309 ObjCMessageExpr *NewMsg = 0;
1310 switch (OldMsg->getReceiverKind()) {
1311 case ObjCMessageExpr::Class:
1312 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1313 OldMsg->getValueKind(),
1314 OldMsg->getLeftLoc(),
1315 OldMsg->getClassReceiverTypeInfo(),
1316 OldMsg->getSelector(),
1317 SelLocs,
1318 OldMsg->getMethodDecl(),
1319 RHS,
1320 OldMsg->getRightLoc(),
1321 OldMsg->isImplicit());
1322 break;
1323
1324 case ObjCMessageExpr::Instance:
1325 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1326 OldMsg->getValueKind(),
1327 OldMsg->getLeftLoc(),
1328 Base,
1329 OldMsg->getSelector(),
1330 SelLocs,
1331 OldMsg->getMethodDecl(),
1332 RHS,
1333 OldMsg->getRightLoc(),
1334 OldMsg->isImplicit());
1335 break;
1336
1337 case ObjCMessageExpr::SuperClass:
1338 case ObjCMessageExpr::SuperInstance:
1339 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340 OldMsg->getValueKind(),
1341 OldMsg->getLeftLoc(),
1342 OldMsg->getSuperLoc(),
1343 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1344 OldMsg->getSuperType(),
1345 OldMsg->getSelector(),
1346 SelLocs,
1347 OldMsg->getMethodDecl(),
1348 RHS,
1349 OldMsg->getRightLoc(),
1350 OldMsg->isImplicit());
1351 break;
1352 }
1353
1354 Stmt *Replacement = SynthMessageExpr(NewMsg);
1355 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1356 return Replacement;
1357}
1358
1359Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1360 SourceRange OldRange = PseudoOp->getSourceRange();
1361
1362 // We just magically know some things about the structure of this
1363 // expression.
1364 ObjCMessageExpr *OldMsg =
1365 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1366
1367 // Because the rewriter doesn't allow us to rewrite rewritten code,
1368 // we need to suppress rewriting the sub-statements.
1369 Expr *Base = 0;
1370 {
1371 DisableReplaceStmtScope S(*this);
1372
1373 // Rebuild the base expression if we have one.
1374 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1375 Base = OldMsg->getInstanceReceiver();
1376 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1377 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1378 }
1379 }
1380
1381 // Intentionally empty.
1382 SmallVector<SourceLocation, 1> SelLocs;
1383 SmallVector<Expr*, 1> Args;
1384
1385 ObjCMessageExpr *NewMsg = 0;
1386 switch (OldMsg->getReceiverKind()) {
1387 case ObjCMessageExpr::Class:
1388 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1389 OldMsg->getValueKind(),
1390 OldMsg->getLeftLoc(),
1391 OldMsg->getClassReceiverTypeInfo(),
1392 OldMsg->getSelector(),
1393 SelLocs,
1394 OldMsg->getMethodDecl(),
1395 Args,
1396 OldMsg->getRightLoc(),
1397 OldMsg->isImplicit());
1398 break;
1399
1400 case ObjCMessageExpr::Instance:
1401 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1402 OldMsg->getValueKind(),
1403 OldMsg->getLeftLoc(),
1404 Base,
1405 OldMsg->getSelector(),
1406 SelLocs,
1407 OldMsg->getMethodDecl(),
1408 Args,
1409 OldMsg->getRightLoc(),
1410 OldMsg->isImplicit());
1411 break;
1412
1413 case ObjCMessageExpr::SuperClass:
1414 case ObjCMessageExpr::SuperInstance:
1415 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1416 OldMsg->getValueKind(),
1417 OldMsg->getLeftLoc(),
1418 OldMsg->getSuperLoc(),
1419 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1420 OldMsg->getSuperType(),
1421 OldMsg->getSelector(),
1422 SelLocs,
1423 OldMsg->getMethodDecl(),
1424 Args,
1425 OldMsg->getRightLoc(),
1426 OldMsg->isImplicit());
1427 break;
1428 }
1429
1430 Stmt *Replacement = SynthMessageExpr(NewMsg);
1431 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1432 return Replacement;
1433}
1434
1435/// SynthCountByEnumWithState - To print:
1436/// ((unsigned int (*)
1437/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1438/// (void *)objc_msgSend)((id)l_collection,
1439/// sel_registerName(
1440/// "countByEnumeratingWithState:objects:count:"),
1441/// &enumState,
1442/// (id *)__rw_items, (unsigned int)16)
1443///
1444void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1445 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1446 "id *, unsigned int))(void *)objc_msgSend)";
1447 buf += "\n\t\t";
1448 buf += "((id)l_collection,\n\t\t";
1449 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1450 buf += "\n\t\t";
1451 buf += "&enumState, "
1452 "(id *)__rw_items, (unsigned int)16)";
1453}
1454
1455/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1456/// statement to exit to its outer synthesized loop.
1457///
1458Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1459 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1460 return S;
1461 // replace break with goto __break_label
1462 std::string buf;
1463
1464 SourceLocation startLoc = S->getLocStart();
1465 buf = "goto __break_label_";
1466 buf += utostr(ObjCBcLabelNo.back());
1467 ReplaceText(startLoc, strlen("break"), buf);
1468
1469 return 0;
1470}
1471
1472/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1473/// statement to continue with its inner synthesized loop.
1474///
1475Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1476 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1477 return S;
1478 // replace continue with goto __continue_label
1479 std::string buf;
1480
1481 SourceLocation startLoc = S->getLocStart();
1482 buf = "goto __continue_label_";
1483 buf += utostr(ObjCBcLabelNo.back());
1484 ReplaceText(startLoc, strlen("continue"), buf);
1485
1486 return 0;
1487}
1488
1489/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1490/// It rewrites:
1491/// for ( type elem in collection) { stmts; }
1492
1493/// Into:
1494/// {
1495/// type elem;
1496/// struct __objcFastEnumerationState enumState = { 0 };
1497/// id __rw_items[16];
1498/// id l_collection = (id)collection;
1499/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1500/// objects:__rw_items count:16];
1501/// if (limit) {
1502/// unsigned long startMutations = *enumState.mutationsPtr;
1503/// do {
1504/// unsigned long counter = 0;
1505/// do {
1506/// if (startMutations != *enumState.mutationsPtr)
1507/// objc_enumerationMutation(l_collection);
1508/// elem = (type)enumState.itemsPtr[counter++];
1509/// stmts;
1510/// __continue_label: ;
1511/// } while (counter < limit);
1512/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1513/// objects:__rw_items count:16]);
1514/// elem = nil;
1515/// __break_label: ;
1516/// }
1517/// else
1518/// elem = nil;
1519/// }
1520///
1521Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1522 SourceLocation OrigEnd) {
1523 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1524 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1525 "ObjCForCollectionStmt Statement stack mismatch");
1526 assert(!ObjCBcLabelNo.empty() &&
1527 "ObjCForCollectionStmt - Label No stack empty");
1528
1529 SourceLocation startLoc = S->getLocStart();
1530 const char *startBuf = SM->getCharacterData(startLoc);
1531 StringRef elementName;
1532 std::string elementTypeAsString;
1533 std::string buf;
1534 buf = "\n{\n\t";
1535 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1536 // type elem;
1537 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1538 QualType ElementType = cast<ValueDecl>(D)->getType();
1539 if (ElementType->isObjCQualifiedIdType() ||
1540 ElementType->isObjCQualifiedInterfaceType())
1541 // Simply use 'id' for all qualified types.
1542 elementTypeAsString = "id";
1543 else
1544 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1545 buf += elementTypeAsString;
1546 buf += " ";
1547 elementName = D->getName();
1548 buf += elementName;
1549 buf += ";\n\t";
1550 }
1551 else {
1552 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1553 elementName = DR->getDecl()->getName();
1554 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1555 if (VD->getType()->isObjCQualifiedIdType() ||
1556 VD->getType()->isObjCQualifiedInterfaceType())
1557 // Simply use 'id' for all qualified types.
1558 elementTypeAsString = "id";
1559 else
1560 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1561 }
1562
1563 // struct __objcFastEnumerationState enumState = { 0 };
1564 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1565 // id __rw_items[16];
1566 buf += "id __rw_items[16];\n\t";
1567 // id l_collection = (id)
1568 buf += "id l_collection = (id)";
1569 // Find start location of 'collection' the hard way!
1570 const char *startCollectionBuf = startBuf;
1571 startCollectionBuf += 3; // skip 'for'
1572 startCollectionBuf = strchr(startCollectionBuf, '(');
1573 startCollectionBuf++; // skip '('
1574 // find 'in' and skip it.
1575 while (*startCollectionBuf != ' ' ||
1576 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1577 (*(startCollectionBuf+3) != ' ' &&
1578 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1579 startCollectionBuf++;
1580 startCollectionBuf += 3;
1581
1582 // Replace: "for (type element in" with string constructed thus far.
1583 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1584 // Replace ')' in for '(' type elem in collection ')' with ';'
1585 SourceLocation rightParenLoc = S->getRParenLoc();
1586 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1587 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1588 buf = ";\n\t";
1589
1590 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1591 // objects:__rw_items count:16];
1592 // which is synthesized into:
1593 // unsigned int limit =
1594 // ((unsigned int (*)
1595 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1596 // (void *)objc_msgSend)((id)l_collection,
1597 // sel_registerName(
1598 // "countByEnumeratingWithState:objects:count:"),
1599 // (struct __objcFastEnumerationState *)&state,
1600 // (id *)__rw_items, (unsigned int)16);
1601 buf += "unsigned long limit =\n\t\t";
1602 SynthCountByEnumWithState(buf);
1603 buf += ";\n\t";
1604 /// if (limit) {
1605 /// unsigned long startMutations = *enumState.mutationsPtr;
1606 /// do {
1607 /// unsigned long counter = 0;
1608 /// do {
1609 /// if (startMutations != *enumState.mutationsPtr)
1610 /// objc_enumerationMutation(l_collection);
1611 /// elem = (type)enumState.itemsPtr[counter++];
1612 buf += "if (limit) {\n\t";
1613 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1614 buf += "do {\n\t\t";
1615 buf += "unsigned long counter = 0;\n\t\t";
1616 buf += "do {\n\t\t\t";
1617 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1618 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1619 buf += elementName;
1620 buf += " = (";
1621 buf += elementTypeAsString;
1622 buf += ")enumState.itemsPtr[counter++];";
1623 // Replace ')' in for '(' type elem in collection ')' with all of these.
1624 ReplaceText(lparenLoc, 1, buf);
1625
1626 /// __continue_label: ;
1627 /// } while (counter < limit);
1628 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1629 /// objects:__rw_items count:16]);
1630 /// elem = nil;
1631 /// __break_label: ;
1632 /// }
1633 /// else
1634 /// elem = nil;
1635 /// }
1636 ///
1637 buf = ";\n\t";
1638 buf += "__continue_label_";
1639 buf += utostr(ObjCBcLabelNo.back());
1640 buf += ": ;";
1641 buf += "\n\t\t";
1642 buf += "} while (counter < limit);\n\t";
1643 buf += "} while (limit = ";
1644 SynthCountByEnumWithState(buf);
1645 buf += ");\n\t";
1646 buf += elementName;
1647 buf += " = ((";
1648 buf += elementTypeAsString;
1649 buf += ")0);\n\t";
1650 buf += "__break_label_";
1651 buf += utostr(ObjCBcLabelNo.back());
1652 buf += ": ;\n\t";
1653 buf += "}\n\t";
1654 buf += "else\n\t\t";
1655 buf += elementName;
1656 buf += " = ((";
1657 buf += elementTypeAsString;
1658 buf += ")0);\n\t";
1659 buf += "}\n";
1660
1661 // Insert all these *after* the statement body.
1662 // FIXME: If this should support Obj-C++, support CXXTryStmt
1663 if (isa<CompoundStmt>(S->getBody())) {
1664 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1665 InsertText(endBodyLoc, buf);
1666 } else {
1667 /* Need to treat single statements specially. For example:
1668 *
1669 * for (A *a in b) if (stuff()) break;
1670 * for (A *a in b) xxxyy;
1671 *
1672 * The following code simply scans ahead to the semi to find the actual end.
1673 */
1674 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1675 const char *semiBuf = strchr(stmtBuf, ';');
1676 assert(semiBuf && "Can't find ';'");
1677 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1678 InsertText(endBodyLoc, buf);
1679 }
1680 Stmts.pop_back();
1681 ObjCBcLabelNo.pop_back();
1682 return 0;
1683}
1684
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001685static void Write_RethrowObject(std::string &buf) {
1686 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1687 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1688 buf += "\tid rethrow;\n";
1689 buf += "\t} _fin_force_rethow(_rethrow);";
1690}
1691
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001692/// RewriteObjCSynchronizedStmt -
1693/// This routine rewrites @synchronized(expr) stmt;
1694/// into:
1695/// objc_sync_enter(expr);
1696/// @try stmt @finally { objc_sync_exit(expr); }
1697///
1698Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1699 // Get the start location and compute the semi location.
1700 SourceLocation startLoc = S->getLocStart();
1701 const char *startBuf = SM->getCharacterData(startLoc);
1702
1703 assert((*startBuf == '@') && "bogus @synchronized location");
1704
1705 std::string buf;
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001706 buf = "{ id volatile _rethrow = 0; objc_sync_enter((id)";
1707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001708 const char *lparenBuf = startBuf;
1709 while (*lparenBuf != '(') lparenBuf++;
1710 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001711 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1712 const char *endBuf = SM->getCharacterData(endLoc);
1713 while (*endBuf != ')') endBuf--;
1714 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1715 buf = ");\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001716 buf += "try ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001717 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001718
1719 SourceLocation startLBraceLoc = S->getSynchBody()->getLocEnd();
1720 const char *startLBraceBuf = SM->getCharacterData(startLBraceLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001721
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001722 assert((*startLBraceBuf == '}') && "bogus @synchronized block");
1723
1724 SourceLocation lastCurlyLoc = startLBraceLoc;
1725
1726 buf = "} catch (id e) {_rethrow = e;}\n";
1727 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001728
1729 std::string syncBuf;
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001730 syncBuf += "\n\tobjc_sync_exit(";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001731
1732 Expr *syncExpr = S->getSynchExpr();
1733 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1734 ? CK_BitCast :
1735 syncExpr->getType()->isBlockPointerType()
1736 ? CK_BlockPointerToObjCPointerCast
1737 : CK_CPointerToObjCPointerCast;
1738 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1739 CK, syncExpr);
1740 std::string syncExprBufS;
1741 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1742 syncExpr->printPretty(syncExprBuf, *Context, 0,
1743 PrintingPolicy(LangOpts));
1744 syncBuf += syncExprBuf.str();
1745 syncBuf += ");";
1746
1747 buf += syncBuf;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001748 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001749 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001750
1751 ReplaceText(lastCurlyLoc, 1, buf);
1752
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001753 return 0;
1754}
1755
1756void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1757{
1758 // Perform a bottom up traversal of all children.
1759 for (Stmt::child_range CI = S->children(); CI; ++CI)
1760 if (*CI)
1761 WarnAboutReturnGotoStmts(*CI);
1762
1763 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1764 Diags.Report(Context->getFullLoc(S->getLocStart()),
1765 TryFinallyContainsReturnDiag);
1766 }
1767 return;
1768}
1769
1770void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1771{
1772 // Perform a bottom up traversal of all children.
1773 for (Stmt::child_range CI = S->children(); CI; ++CI)
1774 if (*CI)
1775 HasReturnStmts(*CI, hasReturns);
1776
1777 if (isa<ReturnStmt>(S))
1778 hasReturns = true;
1779 return;
1780}
1781
1782void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1783 // Perform a bottom up traversal of all children.
1784 for (Stmt::child_range CI = S->children(); CI; ++CI)
1785 if (*CI) {
1786 RewriteTryReturnStmts(*CI);
1787 }
1788 if (isa<ReturnStmt>(S)) {
1789 SourceLocation startLoc = S->getLocStart();
1790 const char *startBuf = SM->getCharacterData(startLoc);
1791
1792 const char *semiBuf = strchr(startBuf, ';');
1793 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1794 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1795
1796 std::string buf;
1797 buf = "{ objc_exception_try_exit(&_stack); return";
1798
1799 ReplaceText(startLoc, 6, buf);
1800 InsertText(onePastSemiLoc, "}");
1801 }
1802 return;
1803}
1804
1805void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1806 // Perform a bottom up traversal of all children.
1807 for (Stmt::child_range CI = S->children(); CI; ++CI)
1808 if (*CI) {
1809 RewriteSyncReturnStmts(*CI, syncExitBuf);
1810 }
1811 if (isa<ReturnStmt>(S)) {
1812 SourceLocation startLoc = S->getLocStart();
1813 const char *startBuf = SM->getCharacterData(startLoc);
1814
1815 const char *semiBuf = strchr(startBuf, ';');
1816 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1817 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1818
1819 std::string buf;
1820 buf = "{ objc_exception_try_exit(&_stack);";
1821 buf += syncExitBuf;
1822 buf += " return";
1823
1824 ReplaceText(startLoc, 6, buf);
1825 InsertText(onePastSemiLoc, "}");
1826 }
1827 return;
1828}
1829
1830Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001831 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001832 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001833 std::string buf;
1834
1835 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001836 if (noCatch)
1837 buf = "{ id volatile _rethrow = 0;\n";
1838 else {
1839 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1840 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001841 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001842 // Get the start location and compute the semi location.
1843 SourceLocation startLoc = S->getLocStart();
1844 const char *startBuf = SM->getCharacterData(startLoc);
1845
1846 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001847 if (finalStmt)
1848 ReplaceText(startLoc, 1, buf);
1849 else
1850 // @try -> try
1851 ReplaceText(startLoc, 1, "");
1852
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001853 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1854 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001855 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001856
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001857 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001858 bool AtRemoved = false;
1859 if (catchDecl) {
1860 QualType t = catchDecl->getType();
1861 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1862 // Should be a pointer to a class.
1863 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1864 if (IDecl) {
1865 std::string Result;
1866 startBuf = SM->getCharacterData(startLoc);
1867 assert((*startBuf == '@') && "bogus @catch location");
1868 SourceLocation rParenLoc = Catch->getRParenLoc();
1869 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1870
1871 // _objc_exc_Foo *_e as argument to catch.
1872 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1873 Result += " *_"; Result += catchDecl->getNameAsString();
1874 Result += ")";
1875 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1876 // Foo *e = (Foo *)_e;
1877 Result.clear();
1878 Result = "{ ";
1879 Result += IDecl->getNameAsString();
1880 Result += " *"; Result += catchDecl->getNameAsString();
1881 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1882 Result += "_"; Result += catchDecl->getNameAsString();
1883
1884 Result += "; ";
1885 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1886 ReplaceText(lBraceLoc, 1, Result);
1887 AtRemoved = true;
1888 }
1889 }
1890 }
1891 if (!AtRemoved)
1892 // @catch -> catch
1893 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001895 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001896 if (finalStmt) {
1897 buf.clear();
1898 if (noCatch)
1899 buf = "catch (id e) {_rethrow = e;}\n";
1900 else
1901 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1902
1903 SourceLocation startFinalLoc = finalStmt->getLocStart();
1904 ReplaceText(startFinalLoc, 8, buf);
1905 Stmt *body = finalStmt->getFinallyBody();
1906 SourceLocation startFinalBodyLoc = body->getLocStart();
1907 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001908 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001909 ReplaceText(startFinalBodyLoc, 1, buf);
1910
1911 SourceLocation endFinalBodyLoc = body->getLocEnd();
1912 ReplaceText(endFinalBodyLoc, 1, "}\n}");
1913 }
1914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001915 return 0;
1916}
1917
1918// This can't be done with ReplaceStmt(S, ThrowExpr), since
1919// the throw expression is typically a message expression that's already
1920// been rewritten! (which implies the SourceLocation's are invalid).
1921Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1922 // Get the start location and compute the semi location.
1923 SourceLocation startLoc = S->getLocStart();
1924 const char *startBuf = SM->getCharacterData(startLoc);
1925
1926 assert((*startBuf == '@') && "bogus @throw location");
1927
1928 std::string buf;
1929 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1930 if (S->getThrowExpr())
1931 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001932 else
1933 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001934
1935 // handle "@ throw" correctly.
1936 const char *wBuf = strchr(startBuf, 'w');
1937 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1938 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1939
1940 const char *semiBuf = strchr(startBuf, ';');
1941 assert((*semiBuf == ';') && "@throw: can't find ';'");
1942 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001943 if (S->getThrowExpr())
1944 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001945 return 0;
1946}
1947
1948Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1949 // Create a new string expression.
1950 QualType StrType = Context->getPointerType(Context->CharTy);
1951 std::string StrEncoding;
1952 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1953 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1954 StringLiteral::Ascii, false,
1955 StrType, SourceLocation());
1956 ReplaceStmt(Exp, Replacement);
1957
1958 // Replace this subexpr in the parent.
1959 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1960 return Replacement;
1961}
1962
1963Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1964 if (!SelGetUidFunctionDecl)
1965 SynthSelGetUidFunctionDecl();
1966 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1967 // Create a call to sel_registerName("selName").
1968 SmallVector<Expr*, 8> SelExprs;
1969 QualType argType = Context->getPointerType(Context->CharTy);
1970 SelExprs.push_back(StringLiteral::Create(*Context,
1971 Exp->getSelector().getAsString(),
1972 StringLiteral::Ascii, false,
1973 argType, SourceLocation()));
1974 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1975 &SelExprs[0], SelExprs.size());
1976 ReplaceStmt(Exp, SelExp);
1977 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1978 return SelExp;
1979}
1980
1981CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1982 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1983 SourceLocation EndLoc) {
1984 // Get the type, we will need to reference it in a couple spots.
1985 QualType msgSendType = FD->getType();
1986
1987 // Create a reference to the objc_msgSend() declaration.
1988 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001989 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001990
1991 // Now, we cast the reference to a pointer to the objc_msgSend type.
1992 QualType pToFunc = Context->getPointerType(msgSendType);
1993 ImplicitCastExpr *ICE =
1994 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1995 DRE, 0, VK_RValue);
1996
1997 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1998
1999 CallExpr *Exp =
2000 new (Context) CallExpr(*Context, ICE, args, nargs,
2001 FT->getCallResultType(*Context),
2002 VK_RValue, EndLoc);
2003 return Exp;
2004}
2005
2006static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2007 const char *&startRef, const char *&endRef) {
2008 while (startBuf < endBuf) {
2009 if (*startBuf == '<')
2010 startRef = startBuf; // mark the start.
2011 if (*startBuf == '>') {
2012 if (startRef && *startRef == '<') {
2013 endRef = startBuf; // mark the end.
2014 return true;
2015 }
2016 return false;
2017 }
2018 startBuf++;
2019 }
2020 return false;
2021}
2022
2023static void scanToNextArgument(const char *&argRef) {
2024 int angle = 0;
2025 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2026 if (*argRef == '<')
2027 angle++;
2028 else if (*argRef == '>')
2029 angle--;
2030 argRef++;
2031 }
2032 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2033}
2034
2035bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2036 if (T->isObjCQualifiedIdType())
2037 return true;
2038 if (const PointerType *PT = T->getAs<PointerType>()) {
2039 if (PT->getPointeeType()->isObjCQualifiedIdType())
2040 return true;
2041 }
2042 if (T->isObjCObjectPointerType()) {
2043 T = T->getPointeeType();
2044 return T->isObjCQualifiedInterfaceType();
2045 }
2046 if (T->isArrayType()) {
2047 QualType ElemTy = Context->getBaseElementType(T);
2048 return needToScanForQualifiers(ElemTy);
2049 }
2050 return false;
2051}
2052
2053void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2054 QualType Type = E->getType();
2055 if (needToScanForQualifiers(Type)) {
2056 SourceLocation Loc, EndLoc;
2057
2058 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2059 Loc = ECE->getLParenLoc();
2060 EndLoc = ECE->getRParenLoc();
2061 } else {
2062 Loc = E->getLocStart();
2063 EndLoc = E->getLocEnd();
2064 }
2065 // This will defend against trying to rewrite synthesized expressions.
2066 if (Loc.isInvalid() || EndLoc.isInvalid())
2067 return;
2068
2069 const char *startBuf = SM->getCharacterData(Loc);
2070 const char *endBuf = SM->getCharacterData(EndLoc);
2071 const char *startRef = 0, *endRef = 0;
2072 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2073 // Get the locations of the startRef, endRef.
2074 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2075 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2076 // Comment out the protocol references.
2077 InsertText(LessLoc, "/*");
2078 InsertText(GreaterLoc, "*/");
2079 }
2080 }
2081}
2082
2083void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2084 SourceLocation Loc;
2085 QualType Type;
2086 const FunctionProtoType *proto = 0;
2087 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2088 Loc = VD->getLocation();
2089 Type = VD->getType();
2090 }
2091 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2092 Loc = FD->getLocation();
2093 // Check for ObjC 'id' and class types that have been adorned with protocol
2094 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2095 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2096 assert(funcType && "missing function type");
2097 proto = dyn_cast<FunctionProtoType>(funcType);
2098 if (!proto)
2099 return;
2100 Type = proto->getResultType();
2101 }
2102 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2103 Loc = FD->getLocation();
2104 Type = FD->getType();
2105 }
2106 else
2107 return;
2108
2109 if (needToScanForQualifiers(Type)) {
2110 // Since types are unique, we need to scan the buffer.
2111
2112 const char *endBuf = SM->getCharacterData(Loc);
2113 const char *startBuf = endBuf;
2114 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2115 startBuf--; // scan backward (from the decl location) for return type.
2116 const char *startRef = 0, *endRef = 0;
2117 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2118 // Get the locations of the startRef, endRef.
2119 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2120 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2121 // Comment out the protocol references.
2122 InsertText(LessLoc, "/*");
2123 InsertText(GreaterLoc, "*/");
2124 }
2125 }
2126 if (!proto)
2127 return; // most likely, was a variable
2128 // Now check arguments.
2129 const char *startBuf = SM->getCharacterData(Loc);
2130 const char *startFuncBuf = startBuf;
2131 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2132 if (needToScanForQualifiers(proto->getArgType(i))) {
2133 // Since types are unique, we need to scan the buffer.
2134
2135 const char *endBuf = startBuf;
2136 // scan forward (from the decl location) for argument types.
2137 scanToNextArgument(endBuf);
2138 const char *startRef = 0, *endRef = 0;
2139 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2140 // Get the locations of the startRef, endRef.
2141 SourceLocation LessLoc =
2142 Loc.getLocWithOffset(startRef-startFuncBuf);
2143 SourceLocation GreaterLoc =
2144 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2145 // Comment out the protocol references.
2146 InsertText(LessLoc, "/*");
2147 InsertText(GreaterLoc, "*/");
2148 }
2149 startBuf = ++endBuf;
2150 }
2151 else {
2152 // If the function name is derived from a macro expansion, then the
2153 // argument buffer will not follow the name. Need to speak with Chris.
2154 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2155 startBuf++; // scan forward (from the decl location) for argument types.
2156 startBuf++;
2157 }
2158 }
2159}
2160
2161void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2162 QualType QT = ND->getType();
2163 const Type* TypePtr = QT->getAs<Type>();
2164 if (!isa<TypeOfExprType>(TypePtr))
2165 return;
2166 while (isa<TypeOfExprType>(TypePtr)) {
2167 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2168 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2169 TypePtr = QT->getAs<Type>();
2170 }
2171 // FIXME. This will not work for multiple declarators; as in:
2172 // __typeof__(a) b,c,d;
2173 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2174 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2175 const char *startBuf = SM->getCharacterData(DeclLoc);
2176 if (ND->getInit()) {
2177 std::string Name(ND->getNameAsString());
2178 TypeAsString += " " + Name + " = ";
2179 Expr *E = ND->getInit();
2180 SourceLocation startLoc;
2181 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2182 startLoc = ECE->getLParenLoc();
2183 else
2184 startLoc = E->getLocStart();
2185 startLoc = SM->getExpansionLoc(startLoc);
2186 const char *endBuf = SM->getCharacterData(startLoc);
2187 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2188 }
2189 else {
2190 SourceLocation X = ND->getLocEnd();
2191 X = SM->getExpansionLoc(X);
2192 const char *endBuf = SM->getCharacterData(X);
2193 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2194 }
2195}
2196
2197// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2198void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2199 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2200 SmallVector<QualType, 16> ArgTys;
2201 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2202 QualType getFuncType =
2203 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2204 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2205 SourceLocation(),
2206 SourceLocation(),
2207 SelGetUidIdent, getFuncType, 0,
2208 SC_Extern,
2209 SC_None, false);
2210}
2211
2212void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2213 // declared in <objc/objc.h>
2214 if (FD->getIdentifier() &&
2215 FD->getName() == "sel_registerName") {
2216 SelGetUidFunctionDecl = FD;
2217 return;
2218 }
2219 RewriteObjCQualifiedInterfaceTypes(FD);
2220}
2221
2222void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2223 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2224 const char *argPtr = TypeString.c_str();
2225 if (!strchr(argPtr, '^')) {
2226 Str += TypeString;
2227 return;
2228 }
2229 while (*argPtr) {
2230 Str += (*argPtr == '^' ? '*' : *argPtr);
2231 argPtr++;
2232 }
2233}
2234
2235// FIXME. Consolidate this routine with RewriteBlockPointerType.
2236void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2237 ValueDecl *VD) {
2238 QualType Type = VD->getType();
2239 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2240 const char *argPtr = TypeString.c_str();
2241 int paren = 0;
2242 while (*argPtr) {
2243 switch (*argPtr) {
2244 case '(':
2245 Str += *argPtr;
2246 paren++;
2247 break;
2248 case ')':
2249 Str += *argPtr;
2250 paren--;
2251 break;
2252 case '^':
2253 Str += '*';
2254 if (paren == 1)
2255 Str += VD->getNameAsString();
2256 break;
2257 default:
2258 Str += *argPtr;
2259 break;
2260 }
2261 argPtr++;
2262 }
2263}
2264
2265
2266void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2267 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2268 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2269 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2270 if (!proto)
2271 return;
2272 QualType Type = proto->getResultType();
2273 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2274 FdStr += " ";
2275 FdStr += FD->getName();
2276 FdStr += "(";
2277 unsigned numArgs = proto->getNumArgs();
2278 for (unsigned i = 0; i < numArgs; i++) {
2279 QualType ArgType = proto->getArgType(i);
2280 RewriteBlockPointerType(FdStr, ArgType);
2281 if (i+1 < numArgs)
2282 FdStr += ", ";
2283 }
2284 FdStr += ");\n";
2285 InsertText(FunLocStart, FdStr);
2286 CurFunctionDeclToDeclareForBlock = 0;
2287}
2288
2289// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2290void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2291 if (SuperContructorFunctionDecl)
2292 return;
2293 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2294 SmallVector<QualType, 16> ArgTys;
2295 QualType argT = Context->getObjCIdType();
2296 assert(!argT.isNull() && "Can't find 'id' type");
2297 ArgTys.push_back(argT);
2298 ArgTys.push_back(argT);
2299 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2300 &ArgTys[0], ArgTys.size());
2301 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2302 SourceLocation(),
2303 SourceLocation(),
2304 msgSendIdent, msgSendType, 0,
2305 SC_Extern,
2306 SC_None, false);
2307}
2308
2309// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2310void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2311 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2312 SmallVector<QualType, 16> ArgTys;
2313 QualType argT = Context->getObjCIdType();
2314 assert(!argT.isNull() && "Can't find 'id' type");
2315 ArgTys.push_back(argT);
2316 argT = Context->getObjCSelType();
2317 assert(!argT.isNull() && "Can't find 'SEL' type");
2318 ArgTys.push_back(argT);
2319 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2320 &ArgTys[0], ArgTys.size(),
2321 true /*isVariadic*/);
2322 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2323 SourceLocation(),
2324 SourceLocation(),
2325 msgSendIdent, msgSendType, 0,
2326 SC_Extern,
2327 SC_None, false);
2328}
2329
2330// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2331void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2332 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2333 SmallVector<QualType, 16> ArgTys;
2334 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2335 SourceLocation(), SourceLocation(),
2336 &Context->Idents.get("objc_super"));
2337 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2338 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2339 ArgTys.push_back(argT);
2340 argT = Context->getObjCSelType();
2341 assert(!argT.isNull() && "Can't find 'SEL' type");
2342 ArgTys.push_back(argT);
2343 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2344 &ArgTys[0], ArgTys.size(),
2345 true /*isVariadic*/);
2346 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2347 SourceLocation(),
2348 SourceLocation(),
2349 msgSendIdent, msgSendType, 0,
2350 SC_Extern,
2351 SC_None, false);
2352}
2353
2354// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2355void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2356 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2357 SmallVector<QualType, 16> ArgTys;
2358 QualType argT = Context->getObjCIdType();
2359 assert(!argT.isNull() && "Can't find 'id' type");
2360 ArgTys.push_back(argT);
2361 argT = Context->getObjCSelType();
2362 assert(!argT.isNull() && "Can't find 'SEL' type");
2363 ArgTys.push_back(argT);
2364 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2365 &ArgTys[0], ArgTys.size(),
2366 true /*isVariadic*/);
2367 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2368 SourceLocation(),
2369 SourceLocation(),
2370 msgSendIdent, msgSendType, 0,
2371 SC_Extern,
2372 SC_None, false);
2373}
2374
2375// SynthMsgSendSuperStretFunctionDecl -
2376// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2377void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2378 IdentifierInfo *msgSendIdent =
2379 &Context->Idents.get("objc_msgSendSuper_stret");
2380 SmallVector<QualType, 16> ArgTys;
2381 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2382 SourceLocation(), SourceLocation(),
2383 &Context->Idents.get("objc_super"));
2384 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2385 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2386 ArgTys.push_back(argT);
2387 argT = Context->getObjCSelType();
2388 assert(!argT.isNull() && "Can't find 'SEL' type");
2389 ArgTys.push_back(argT);
2390 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2391 &ArgTys[0], ArgTys.size(),
2392 true /*isVariadic*/);
2393 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2394 SourceLocation(),
2395 SourceLocation(),
2396 msgSendIdent, msgSendType, 0,
2397 SC_Extern,
2398 SC_None, false);
2399}
2400
2401// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2402void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2403 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2404 SmallVector<QualType, 16> ArgTys;
2405 QualType argT = Context->getObjCIdType();
2406 assert(!argT.isNull() && "Can't find 'id' type");
2407 ArgTys.push_back(argT);
2408 argT = Context->getObjCSelType();
2409 assert(!argT.isNull() && "Can't find 'SEL' type");
2410 ArgTys.push_back(argT);
2411 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2412 &ArgTys[0], ArgTys.size(),
2413 true /*isVariadic*/);
2414 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2415 SourceLocation(),
2416 SourceLocation(),
2417 msgSendIdent, msgSendType, 0,
2418 SC_Extern,
2419 SC_None, false);
2420}
2421
2422// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2423void RewriteModernObjC::SynthGetClassFunctionDecl() {
2424 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2425 SmallVector<QualType, 16> ArgTys;
2426 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2427 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2428 &ArgTys[0], ArgTys.size());
2429 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430 SourceLocation(),
2431 SourceLocation(),
2432 getClassIdent, getClassType, 0,
2433 SC_Extern,
2434 SC_None, false);
2435}
2436
2437// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2438void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2439 IdentifierInfo *getSuperClassIdent =
2440 &Context->Idents.get("class_getSuperclass");
2441 SmallVector<QualType, 16> ArgTys;
2442 ArgTys.push_back(Context->getObjCClassType());
2443 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2444 &ArgTys[0], ArgTys.size());
2445 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2446 SourceLocation(),
2447 SourceLocation(),
2448 getSuperClassIdent,
2449 getClassType, 0,
2450 SC_Extern,
2451 SC_None,
2452 false);
2453}
2454
2455// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2456void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2457 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2458 SmallVector<QualType, 16> ArgTys;
2459 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2460 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2461 &ArgTys[0], ArgTys.size());
2462 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2463 SourceLocation(),
2464 SourceLocation(),
2465 getClassIdent, getClassType, 0,
2466 SC_Extern,
2467 SC_None, false);
2468}
2469
2470Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2471 QualType strType = getConstantStringStructType();
2472
2473 std::string S = "__NSConstantStringImpl_";
2474
2475 std::string tmpName = InFileName;
2476 unsigned i;
2477 for (i=0; i < tmpName.length(); i++) {
2478 char c = tmpName.at(i);
2479 // replace any non alphanumeric characters with '_'.
2480 if (!isalpha(c) && (c < '0' || c > '9'))
2481 tmpName[i] = '_';
2482 }
2483 S += tmpName;
2484 S += "_";
2485 S += utostr(NumObjCStringLiterals++);
2486
2487 Preamble += "static __NSConstantStringImpl " + S;
2488 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2489 Preamble += "0x000007c8,"; // utf8_str
2490 // The pretty printer for StringLiteral handles escape characters properly.
2491 std::string prettyBufS;
2492 llvm::raw_string_ostream prettyBuf(prettyBufS);
2493 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2494 PrintingPolicy(LangOpts));
2495 Preamble += prettyBuf.str();
2496 Preamble += ",";
2497 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2498
2499 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2500 SourceLocation(), &Context->Idents.get(S),
2501 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002502 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002503 SourceLocation());
2504 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2505 Context->getPointerType(DRE->getType()),
2506 VK_RValue, OK_Ordinary,
2507 SourceLocation());
2508 // cast to NSConstantString *
2509 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2510 CK_CPointerToObjCPointerCast, Unop);
2511 ReplaceStmt(Exp, cast);
2512 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2513 return cast;
2514}
2515
2516// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2517QualType RewriteModernObjC::getSuperStructType() {
2518 if (!SuperStructDecl) {
2519 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2520 SourceLocation(), SourceLocation(),
2521 &Context->Idents.get("objc_super"));
2522 QualType FieldTypes[2];
2523
2524 // struct objc_object *receiver;
2525 FieldTypes[0] = Context->getObjCIdType();
2526 // struct objc_class *super;
2527 FieldTypes[1] = Context->getObjCClassType();
2528
2529 // Create fields
2530 for (unsigned i = 0; i < 2; ++i) {
2531 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2532 SourceLocation(),
2533 SourceLocation(), 0,
2534 FieldTypes[i], 0,
2535 /*BitWidth=*/0,
2536 /*Mutable=*/false,
2537 /*HasInit=*/false));
2538 }
2539
2540 SuperStructDecl->completeDefinition();
2541 }
2542 return Context->getTagDeclType(SuperStructDecl);
2543}
2544
2545QualType RewriteModernObjC::getConstantStringStructType() {
2546 if (!ConstantStringDecl) {
2547 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2548 SourceLocation(), SourceLocation(),
2549 &Context->Idents.get("__NSConstantStringImpl"));
2550 QualType FieldTypes[4];
2551
2552 // struct objc_object *receiver;
2553 FieldTypes[0] = Context->getObjCIdType();
2554 // int flags;
2555 FieldTypes[1] = Context->IntTy;
2556 // char *str;
2557 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2558 // long length;
2559 FieldTypes[3] = Context->LongTy;
2560
2561 // Create fields
2562 for (unsigned i = 0; i < 4; ++i) {
2563 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2564 ConstantStringDecl,
2565 SourceLocation(),
2566 SourceLocation(), 0,
2567 FieldTypes[i], 0,
2568 /*BitWidth=*/0,
2569 /*Mutable=*/true,
2570 /*HasInit=*/false));
2571 }
2572
2573 ConstantStringDecl->completeDefinition();
2574 }
2575 return Context->getTagDeclType(ConstantStringDecl);
2576}
2577
2578Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2579 SourceLocation StartLoc,
2580 SourceLocation EndLoc) {
2581 if (!SelGetUidFunctionDecl)
2582 SynthSelGetUidFunctionDecl();
2583 if (!MsgSendFunctionDecl)
2584 SynthMsgSendFunctionDecl();
2585 if (!MsgSendSuperFunctionDecl)
2586 SynthMsgSendSuperFunctionDecl();
2587 if (!MsgSendStretFunctionDecl)
2588 SynthMsgSendStretFunctionDecl();
2589 if (!MsgSendSuperStretFunctionDecl)
2590 SynthMsgSendSuperStretFunctionDecl();
2591 if (!MsgSendFpretFunctionDecl)
2592 SynthMsgSendFpretFunctionDecl();
2593 if (!GetClassFunctionDecl)
2594 SynthGetClassFunctionDecl();
2595 if (!GetSuperClassFunctionDecl)
2596 SynthGetSuperClassFunctionDecl();
2597 if (!GetMetaClassFunctionDecl)
2598 SynthGetMetaClassFunctionDecl();
2599
2600 // default to objc_msgSend().
2601 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2602 // May need to use objc_msgSend_stret() as well.
2603 FunctionDecl *MsgSendStretFlavor = 0;
2604 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2605 QualType resultType = mDecl->getResultType();
2606 if (resultType->isRecordType())
2607 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2608 else if (resultType->isRealFloatingType())
2609 MsgSendFlavor = MsgSendFpretFunctionDecl;
2610 }
2611
2612 // Synthesize a call to objc_msgSend().
2613 SmallVector<Expr*, 8> MsgExprs;
2614 switch (Exp->getReceiverKind()) {
2615 case ObjCMessageExpr::SuperClass: {
2616 MsgSendFlavor = MsgSendSuperFunctionDecl;
2617 if (MsgSendStretFlavor)
2618 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2619 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2620
2621 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2622
2623 SmallVector<Expr*, 4> InitExprs;
2624
2625 // set the receiver to self, the first argument to all methods.
2626 InitExprs.push_back(
2627 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2628 CK_BitCast,
2629 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002630 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002631 Context->getObjCIdType(),
2632 VK_RValue,
2633 SourceLocation()))
2634 ); // set the 'receiver'.
2635
2636 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2637 SmallVector<Expr*, 8> ClsExprs;
2638 QualType argType = Context->getPointerType(Context->CharTy);
2639 ClsExprs.push_back(StringLiteral::Create(*Context,
2640 ClassDecl->getIdentifier()->getName(),
2641 StringLiteral::Ascii, false,
2642 argType, SourceLocation()));
2643 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2644 &ClsExprs[0],
2645 ClsExprs.size(),
2646 StartLoc,
2647 EndLoc);
2648 // (Class)objc_getClass("CurrentClass")
2649 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2650 Context->getObjCClassType(),
2651 CK_BitCast, Cls);
2652 ClsExprs.clear();
2653 ClsExprs.push_back(ArgExpr);
2654 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2655 &ClsExprs[0], ClsExprs.size(),
2656 StartLoc, EndLoc);
2657
2658 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2659 // To turn off a warning, type-cast to 'id'
2660 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2661 NoTypeInfoCStyleCastExpr(Context,
2662 Context->getObjCIdType(),
2663 CK_BitCast, Cls));
2664 // struct objc_super
2665 QualType superType = getSuperStructType();
2666 Expr *SuperRep;
2667
2668 if (LangOpts.MicrosoftExt) {
2669 SynthSuperContructorFunctionDecl();
2670 // Simulate a contructor call...
2671 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002672 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002673 SourceLocation());
2674 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2675 InitExprs.size(),
2676 superType, VK_LValue,
2677 SourceLocation());
2678 // The code for super is a little tricky to prevent collision with
2679 // the structure definition in the header. The rewriter has it's own
2680 // internal definition (__rw_objc_super) that is uses. This is why
2681 // we need the cast below. For example:
2682 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2683 //
2684 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2685 Context->getPointerType(SuperRep->getType()),
2686 VK_RValue, OK_Ordinary,
2687 SourceLocation());
2688 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2689 Context->getPointerType(superType),
2690 CK_BitCast, SuperRep);
2691 } else {
2692 // (struct objc_super) { <exprs from above> }
2693 InitListExpr *ILE =
2694 new (Context) InitListExpr(*Context, SourceLocation(),
2695 &InitExprs[0], InitExprs.size(),
2696 SourceLocation());
2697 TypeSourceInfo *superTInfo
2698 = Context->getTrivialTypeSourceInfo(superType);
2699 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2700 superType, VK_LValue,
2701 ILE, false);
2702 // struct objc_super *
2703 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2704 Context->getPointerType(SuperRep->getType()),
2705 VK_RValue, OK_Ordinary,
2706 SourceLocation());
2707 }
2708 MsgExprs.push_back(SuperRep);
2709 break;
2710 }
2711
2712 case ObjCMessageExpr::Class: {
2713 SmallVector<Expr*, 8> ClsExprs;
2714 QualType argType = Context->getPointerType(Context->CharTy);
2715 ObjCInterfaceDecl *Class
2716 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2717 IdentifierInfo *clsName = Class->getIdentifier();
2718 ClsExprs.push_back(StringLiteral::Create(*Context,
2719 clsName->getName(),
2720 StringLiteral::Ascii, false,
2721 argType, SourceLocation()));
2722 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2723 &ClsExprs[0],
2724 ClsExprs.size(),
2725 StartLoc, EndLoc);
2726 MsgExprs.push_back(Cls);
2727 break;
2728 }
2729
2730 case ObjCMessageExpr::SuperInstance:{
2731 MsgSendFlavor = MsgSendSuperFunctionDecl;
2732 if (MsgSendStretFlavor)
2733 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2734 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2735 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2736 SmallVector<Expr*, 4> InitExprs;
2737
2738 InitExprs.push_back(
2739 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2740 CK_BitCast,
2741 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002742 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002743 Context->getObjCIdType(),
2744 VK_RValue, SourceLocation()))
2745 ); // set the 'receiver'.
2746
2747 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2748 SmallVector<Expr*, 8> ClsExprs;
2749 QualType argType = Context->getPointerType(Context->CharTy);
2750 ClsExprs.push_back(StringLiteral::Create(*Context,
2751 ClassDecl->getIdentifier()->getName(),
2752 StringLiteral::Ascii, false, argType,
2753 SourceLocation()));
2754 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2755 &ClsExprs[0],
2756 ClsExprs.size(),
2757 StartLoc, EndLoc);
2758 // (Class)objc_getClass("CurrentClass")
2759 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2760 Context->getObjCClassType(),
2761 CK_BitCast, Cls);
2762 ClsExprs.clear();
2763 ClsExprs.push_back(ArgExpr);
2764 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2765 &ClsExprs[0], ClsExprs.size(),
2766 StartLoc, EndLoc);
2767
2768 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2769 // To turn off a warning, type-cast to 'id'
2770 InitExprs.push_back(
2771 // set 'super class', using class_getSuperclass().
2772 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2773 CK_BitCast, Cls));
2774 // struct objc_super
2775 QualType superType = getSuperStructType();
2776 Expr *SuperRep;
2777
2778 if (LangOpts.MicrosoftExt) {
2779 SynthSuperContructorFunctionDecl();
2780 // Simulate a contructor call...
2781 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002782 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002783 SourceLocation());
2784 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2785 InitExprs.size(),
2786 superType, VK_LValue, SourceLocation());
2787 // The code for super is a little tricky to prevent collision with
2788 // the structure definition in the header. The rewriter has it's own
2789 // internal definition (__rw_objc_super) that is uses. This is why
2790 // we need the cast below. For example:
2791 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2792 //
2793 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2794 Context->getPointerType(SuperRep->getType()),
2795 VK_RValue, OK_Ordinary,
2796 SourceLocation());
2797 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2798 Context->getPointerType(superType),
2799 CK_BitCast, SuperRep);
2800 } else {
2801 // (struct objc_super) { <exprs from above> }
2802 InitListExpr *ILE =
2803 new (Context) InitListExpr(*Context, SourceLocation(),
2804 &InitExprs[0], InitExprs.size(),
2805 SourceLocation());
2806 TypeSourceInfo *superTInfo
2807 = Context->getTrivialTypeSourceInfo(superType);
2808 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2809 superType, VK_RValue, ILE,
2810 false);
2811 }
2812 MsgExprs.push_back(SuperRep);
2813 break;
2814 }
2815
2816 case ObjCMessageExpr::Instance: {
2817 // Remove all type-casts because it may contain objc-style types; e.g.
2818 // Foo<Proto> *.
2819 Expr *recExpr = Exp->getInstanceReceiver();
2820 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2821 recExpr = CE->getSubExpr();
2822 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2823 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2824 ? CK_BlockPointerToObjCPointerCast
2825 : CK_CPointerToObjCPointerCast;
2826
2827 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2828 CK, recExpr);
2829 MsgExprs.push_back(recExpr);
2830 break;
2831 }
2832 }
2833
2834 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2835 SmallVector<Expr*, 8> SelExprs;
2836 QualType argType = Context->getPointerType(Context->CharTy);
2837 SelExprs.push_back(StringLiteral::Create(*Context,
2838 Exp->getSelector().getAsString(),
2839 StringLiteral::Ascii, false,
2840 argType, SourceLocation()));
2841 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2842 &SelExprs[0], SelExprs.size(),
2843 StartLoc,
2844 EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
2847 // Now push any user supplied arguments.
2848 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2849 Expr *userExpr = Exp->getArg(i);
2850 // Make all implicit casts explicit...ICE comes in handy:-)
2851 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2852 // Reuse the ICE type, it is exactly what the doctor ordered.
2853 QualType type = ICE->getType();
2854 if (needToScanForQualifiers(type))
2855 type = Context->getObjCIdType();
2856 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2857 (void)convertBlockPointerToFunctionPointer(type);
2858 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2859 CastKind CK;
2860 if (SubExpr->getType()->isIntegralType(*Context) &&
2861 type->isBooleanType()) {
2862 CK = CK_IntegralToBoolean;
2863 } else if (type->isObjCObjectPointerType()) {
2864 if (SubExpr->getType()->isBlockPointerType()) {
2865 CK = CK_BlockPointerToObjCPointerCast;
2866 } else if (SubExpr->getType()->isPointerType()) {
2867 CK = CK_CPointerToObjCPointerCast;
2868 } else {
2869 CK = CK_BitCast;
2870 }
2871 } else {
2872 CK = CK_BitCast;
2873 }
2874
2875 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2876 }
2877 // Make id<P...> cast into an 'id' cast.
2878 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2879 if (CE->getType()->isObjCQualifiedIdType()) {
2880 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2881 userExpr = CE->getSubExpr();
2882 CastKind CK;
2883 if (userExpr->getType()->isIntegralType(*Context)) {
2884 CK = CK_IntegralToPointer;
2885 } else if (userExpr->getType()->isBlockPointerType()) {
2886 CK = CK_BlockPointerToObjCPointerCast;
2887 } else if (userExpr->getType()->isPointerType()) {
2888 CK = CK_CPointerToObjCPointerCast;
2889 } else {
2890 CK = CK_BitCast;
2891 }
2892 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2893 CK, userExpr);
2894 }
2895 }
2896 MsgExprs.push_back(userExpr);
2897 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2898 // out the argument in the original expression (since we aren't deleting
2899 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2900 //Exp->setArg(i, 0);
2901 }
2902 // Generate the funky cast.
2903 CastExpr *cast;
2904 SmallVector<QualType, 8> ArgTypes;
2905 QualType returnType;
2906
2907 // Push 'id' and 'SEL', the 2 implicit arguments.
2908 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2909 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2910 else
2911 ArgTypes.push_back(Context->getObjCIdType());
2912 ArgTypes.push_back(Context->getObjCSelType());
2913 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2914 // Push any user argument types.
2915 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2916 E = OMD->param_end(); PI != E; ++PI) {
2917 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2918 ? Context->getObjCIdType()
2919 : (*PI)->getType();
2920 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2921 (void)convertBlockPointerToFunctionPointer(t);
2922 ArgTypes.push_back(t);
2923 }
2924 returnType = Exp->getType();
2925 convertToUnqualifiedObjCType(returnType);
2926 (void)convertBlockPointerToFunctionPointer(returnType);
2927 } else {
2928 returnType = Context->getObjCIdType();
2929 }
2930 // Get the type, we will need to reference it in a couple spots.
2931 QualType msgSendType = MsgSendFlavor->getType();
2932
2933 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002934 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002935 VK_LValue, SourceLocation());
2936
2937 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2938 // If we don't do this cast, we get the following bizarre warning/note:
2939 // xx.m:13: warning: function called through a non-compatible type
2940 // xx.m:13: note: if this code is reached, the program will abort
2941 cast = NoTypeInfoCStyleCastExpr(Context,
2942 Context->getPointerType(Context->VoidTy),
2943 CK_BitCast, DRE);
2944
2945 // Now do the "normal" pointer to function cast.
2946 QualType castType =
2947 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2948 // If we don't have a method decl, force a variadic cast.
2949 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2950 castType = Context->getPointerType(castType);
2951 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2952 cast);
2953
2954 // Don't forget the parens to enforce the proper binding.
2955 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2956
2957 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2958 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2959 MsgExprs.size(),
2960 FT->getResultType(), VK_RValue,
2961 EndLoc);
2962 Stmt *ReplacingStmt = CE;
2963 if (MsgSendStretFlavor) {
2964 // We have the method which returns a struct/union. Must also generate
2965 // call to objc_msgSend_stret and hang both varieties on a conditional
2966 // expression which dictate which one to envoke depending on size of
2967 // method's return type.
2968
2969 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002970 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2971 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002972 VK_LValue, SourceLocation());
2973 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2974 cast = NoTypeInfoCStyleCastExpr(Context,
2975 Context->getPointerType(Context->VoidTy),
2976 CK_BitCast, STDRE);
2977 // Now do the "normal" pointer to function cast.
2978 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2979 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2980 castType = Context->getPointerType(castType);
2981 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2982 cast);
2983
2984 // Don't forget the parens to enforce the proper binding.
2985 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2986
2987 FT = msgSendType->getAs<FunctionType>();
2988 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2989 MsgExprs.size(),
2990 FT->getResultType(), VK_RValue,
2991 SourceLocation());
2992
2993 // Build sizeof(returnType)
2994 UnaryExprOrTypeTraitExpr *sizeofExpr =
2995 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2996 Context->getTrivialTypeSourceInfo(returnType),
2997 Context->getSizeType(), SourceLocation(),
2998 SourceLocation());
2999 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3000 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3001 // For X86 it is more complicated and some kind of target specific routine
3002 // is needed to decide what to do.
3003 unsigned IntSize =
3004 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3005 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3006 llvm::APInt(IntSize, 8),
3007 Context->IntTy,
3008 SourceLocation());
3009 BinaryOperator *lessThanExpr =
3010 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3011 VK_RValue, OK_Ordinary, SourceLocation());
3012 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3013 ConditionalOperator *CondExpr =
3014 new (Context) ConditionalOperator(lessThanExpr,
3015 SourceLocation(), CE,
3016 SourceLocation(), STCE,
3017 returnType, VK_RValue, OK_Ordinary);
3018 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3019 CondExpr);
3020 }
3021 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3022 return ReplacingStmt;
3023}
3024
3025Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3026 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3027 Exp->getLocEnd());
3028
3029 // Now do the actual rewrite.
3030 ReplaceStmt(Exp, ReplacingStmt);
3031
3032 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3033 return ReplacingStmt;
3034}
3035
3036// typedef struct objc_object Protocol;
3037QualType RewriteModernObjC::getProtocolType() {
3038 if (!ProtocolTypeDecl) {
3039 TypeSourceInfo *TInfo
3040 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3041 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3042 SourceLocation(), SourceLocation(),
3043 &Context->Idents.get("Protocol"),
3044 TInfo);
3045 }
3046 return Context->getTypeDeclType(ProtocolTypeDecl);
3047}
3048
3049/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3050/// a synthesized/forward data reference (to the protocol's metadata).
3051/// The forward references (and metadata) are generated in
3052/// RewriteModernObjC::HandleTranslationUnit().
3053Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003054 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3055 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003056 IdentifierInfo *ID = &Context->Idents.get(Name);
3057 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3058 SourceLocation(), ID, getProtocolType(), 0,
3059 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003060 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3061 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003062 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3063 Context->getPointerType(DRE->getType()),
3064 VK_RValue, OK_Ordinary, SourceLocation());
3065 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3066 CK_BitCast,
3067 DerefExpr);
3068 ReplaceStmt(Exp, castExpr);
3069 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3070 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3071 return castExpr;
3072
3073}
3074
3075bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3076 const char *endBuf) {
3077 while (startBuf < endBuf) {
3078 if (*startBuf == '#') {
3079 // Skip whitespace.
3080 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3081 ;
3082 if (!strncmp(startBuf, "if", strlen("if")) ||
3083 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3084 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3085 !strncmp(startBuf, "define", strlen("define")) ||
3086 !strncmp(startBuf, "undef", strlen("undef")) ||
3087 !strncmp(startBuf, "else", strlen("else")) ||
3088 !strncmp(startBuf, "elif", strlen("elif")) ||
3089 !strncmp(startBuf, "endif", strlen("endif")) ||
3090 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3091 !strncmp(startBuf, "include", strlen("include")) ||
3092 !strncmp(startBuf, "import", strlen("import")) ||
3093 !strncmp(startBuf, "include_next", strlen("include_next")))
3094 return true;
3095 }
3096 startBuf++;
3097 }
3098 return false;
3099}
3100
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003101/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003102/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003103bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3104 std::string &Result) {
3105 if (Type->isArrayType()) {
3106 QualType ElemTy = Context->getBaseElementType(Type);
3107 return RewriteObjCFieldDeclType(ElemTy, Result);
3108 }
3109 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003110 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3111 if (RD->isCompleteDefinition()) {
3112 if (RD->isStruct())
3113 Result += "\n\tstruct ";
3114 else if (RD->isUnion())
3115 Result += "\n\tunion ";
3116 else
3117 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003118
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003119 Result += RD->getName();
3120 if (TagsDefinedInIvarDecls.count(RD)) {
3121 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003122 Result += " ";
3123 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003124 }
3125 TagsDefinedInIvarDecls.insert(RD);
3126 Result += " {\n";
3127 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003128 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003129 FieldDecl *FD = *i;
3130 RewriteObjCFieldDecl(FD, Result);
3131 }
3132 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003133 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003134 }
3135 }
3136 else if (Type->isEnumeralType()) {
3137 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3138 if (ED->isCompleteDefinition()) {
3139 Result += "\n\tenum ";
3140 Result += ED->getName();
3141 if (TagsDefinedInIvarDecls.count(ED)) {
3142 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003143 Result += " ";
3144 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003145 }
3146 TagsDefinedInIvarDecls.insert(ED);
3147
3148 Result += " {\n";
3149 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3150 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3151 Result += "\t"; Result += EC->getName(); Result += " = ";
3152 llvm::APSInt Val = EC->getInitVal();
3153 Result += Val.toString(10);
3154 Result += ",\n";
3155 }
3156 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003157 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003158 }
3159 }
3160
3161 Result += "\t";
3162 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003163 return false;
3164}
3165
3166
3167/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3168/// It handles elaborated types, as well as enum types in the process.
3169void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3170 std::string &Result) {
3171 QualType Type = fieldDecl->getType();
3172 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003173
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003174 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3175 if (!EleboratedType)
3176 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003177 Result += Name;
3178 if (fieldDecl->isBitField()) {
3179 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3180 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003181 else if (EleboratedType && Type->isArrayType()) {
3182 CanQualType CType = Context->getCanonicalType(Type);
3183 while (isa<ArrayType>(CType)) {
3184 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3185 Result += "[";
3186 llvm::APInt Dim = CAT->getSize();
3187 Result += utostr(Dim.getZExtValue());
3188 Result += "]";
3189 }
3190 CType = CType->getAs<ArrayType>()->getElementType();
3191 }
3192 }
3193
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003194 Result += ";\n";
3195}
3196
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003197/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3198/// an objective-c class with ivars.
3199void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3200 std::string &Result) {
3201 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3202 assert(CDecl->getName() != "" &&
3203 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003204 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003205 SmallVector<ObjCIvarDecl *, 8> IVars;
3206 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003207 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003208 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003209
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003210 SourceLocation LocStart = CDecl->getLocStart();
3211 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003212
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003213 const char *startBuf = SM->getCharacterData(LocStart);
3214 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003215
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003216 // If no ivars and no root or if its root, directly or indirectly,
3217 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003218 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003219 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3220 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3221 ReplaceText(LocStart, endBuf-startBuf, Result);
3222 return;
3223 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003224
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003225 Result += "\nstruct ";
3226 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003227 Result += "_IMPL {\n";
3228
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003229 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003230 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3231 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3232 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003233 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003234 TagsDefinedInIvarDecls.clear();
3235 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3236 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003237
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003238 Result += "};\n";
3239 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3240 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003241 // Mark this struct as having been generated.
3242 if (!ObjCSynthesizedStructs.insert(CDecl))
3243 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003244}
3245
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003246/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3247/// have been referenced in an ivar access expression.
3248void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3249 std::string &Result) {
3250 // write out ivar offset symbols which have been referenced in an ivar
3251 // access expression.
3252 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3253 if (Ivars.empty())
3254 return;
3255 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3256 e = Ivars.end(); i != e; i++) {
3257 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003258 Result += "\n";
3259 if (LangOpts.MicrosoftExt)
3260 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3261 if (LangOpts.MicrosoftExt &&
3262 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3263 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3264 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3265 if (CDecl->getImplementation())
3266 Result += "__declspec(dllexport) ";
3267 }
3268 Result += "extern unsigned long OBJC_IVAR_$_";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003269 Result += CDecl->getName(); Result += "_";
3270 Result += IvarDecl->getName(); Result += ";";
3271 }
3272}
3273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003274//===----------------------------------------------------------------------===//
3275// Meta Data Emission
3276//===----------------------------------------------------------------------===//
3277
3278
3279/// RewriteImplementations - This routine rewrites all method implementations
3280/// and emits meta-data.
3281
3282void RewriteModernObjC::RewriteImplementations() {
3283 int ClsDefCount = ClassImplementation.size();
3284 int CatDefCount = CategoryImplementation.size();
3285
3286 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003287 for (int i = 0; i < ClsDefCount; i++) {
3288 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3289 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3290 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003291 assert(false &&
3292 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003293 RewriteImplementationDecl(OIMP);
3294 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003295
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003296 for (int i = 0; i < CatDefCount; i++) {
3297 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3298 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3299 if (CDecl->isImplicitInterfaceDecl())
3300 assert(false &&
3301 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003302 RewriteImplementationDecl(CIMP);
3303 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003304}
3305
3306void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3307 const std::string &Name,
3308 ValueDecl *VD, bool def) {
3309 assert(BlockByRefDeclNo.count(VD) &&
3310 "RewriteByRefString: ByRef decl missing");
3311 if (def)
3312 ResultStr += "struct ";
3313 ResultStr += "__Block_byref_" + Name +
3314 "_" + utostr(BlockByRefDeclNo[VD]) ;
3315}
3316
3317static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3318 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3319 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3320 return false;
3321}
3322
3323std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3324 StringRef funcName,
3325 std::string Tag) {
3326 const FunctionType *AFT = CE->getFunctionType();
3327 QualType RT = AFT->getResultType();
3328 std::string StructRef = "struct " + Tag;
3329 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3330 funcName.str() + "_" + "block_func_" + utostr(i);
3331
3332 BlockDecl *BD = CE->getBlockDecl();
3333
3334 if (isa<FunctionNoProtoType>(AFT)) {
3335 // No user-supplied arguments. Still need to pass in a pointer to the
3336 // block (to reference imported block decl refs).
3337 S += "(" + StructRef + " *__cself)";
3338 } else if (BD->param_empty()) {
3339 S += "(" + StructRef + " *__cself)";
3340 } else {
3341 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3342 assert(FT && "SynthesizeBlockFunc: No function proto");
3343 S += '(';
3344 // first add the implicit argument.
3345 S += StructRef + " *__cself, ";
3346 std::string ParamStr;
3347 for (BlockDecl::param_iterator AI = BD->param_begin(),
3348 E = BD->param_end(); AI != E; ++AI) {
3349 if (AI != BD->param_begin()) S += ", ";
3350 ParamStr = (*AI)->getNameAsString();
3351 QualType QT = (*AI)->getType();
3352 if (convertBlockPointerToFunctionPointer(QT))
3353 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3354 else
3355 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3356 S += ParamStr;
3357 }
3358 if (FT->isVariadic()) {
3359 if (!BD->param_empty()) S += ", ";
3360 S += "...";
3361 }
3362 S += ')';
3363 }
3364 S += " {\n";
3365
3366 // Create local declarations to avoid rewriting all closure decl ref exprs.
3367 // First, emit a declaration for all "by ref" decls.
3368 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3369 E = BlockByRefDecls.end(); I != E; ++I) {
3370 S += " ";
3371 std::string Name = (*I)->getNameAsString();
3372 std::string TypeString;
3373 RewriteByRefString(TypeString, Name, (*I));
3374 TypeString += " *";
3375 Name = TypeString + Name;
3376 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3377 }
3378 // Next, emit a declaration for all "by copy" declarations.
3379 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3380 E = BlockByCopyDecls.end(); I != E; ++I) {
3381 S += " ";
3382 // Handle nested closure invocation. For example:
3383 //
3384 // void (^myImportedClosure)(void);
3385 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3386 //
3387 // void (^anotherClosure)(void);
3388 // anotherClosure = ^(void) {
3389 // myImportedClosure(); // import and invoke the closure
3390 // };
3391 //
3392 if (isTopLevelBlockPointerType((*I)->getType())) {
3393 RewriteBlockPointerTypeVariable(S, (*I));
3394 S += " = (";
3395 RewriteBlockPointerType(S, (*I)->getType());
3396 S += ")";
3397 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3398 }
3399 else {
3400 std::string Name = (*I)->getNameAsString();
3401 QualType QT = (*I)->getType();
3402 if (HasLocalVariableExternalStorage(*I))
3403 QT = Context->getPointerType(QT);
3404 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3405 S += Name + " = __cself->" +
3406 (*I)->getNameAsString() + "; // bound by copy\n";
3407 }
3408 }
3409 std::string RewrittenStr = RewrittenBlockExprs[CE];
3410 const char *cstr = RewrittenStr.c_str();
3411 while (*cstr++ != '{') ;
3412 S += cstr;
3413 S += "\n";
3414 return S;
3415}
3416
3417std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3418 StringRef funcName,
3419 std::string Tag) {
3420 std::string StructRef = "struct " + Tag;
3421 std::string S = "static void __";
3422
3423 S += funcName;
3424 S += "_block_copy_" + utostr(i);
3425 S += "(" + StructRef;
3426 S += "*dst, " + StructRef;
3427 S += "*src) {";
3428 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3429 E = ImportedBlockDecls.end(); I != E; ++I) {
3430 ValueDecl *VD = (*I);
3431 S += "_Block_object_assign((void*)&dst->";
3432 S += (*I)->getNameAsString();
3433 S += ", (void*)src->";
3434 S += (*I)->getNameAsString();
3435 if (BlockByRefDeclsPtrSet.count((*I)))
3436 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3437 else if (VD->getType()->isBlockPointerType())
3438 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3439 else
3440 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3441 }
3442 S += "}\n";
3443
3444 S += "\nstatic void __";
3445 S += funcName;
3446 S += "_block_dispose_" + utostr(i);
3447 S += "(" + StructRef;
3448 S += "*src) {";
3449 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3450 E = ImportedBlockDecls.end(); I != E; ++I) {
3451 ValueDecl *VD = (*I);
3452 S += "_Block_object_dispose((void*)src->";
3453 S += (*I)->getNameAsString();
3454 if (BlockByRefDeclsPtrSet.count((*I)))
3455 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3456 else if (VD->getType()->isBlockPointerType())
3457 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3458 else
3459 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3460 }
3461 S += "}\n";
3462 return S;
3463}
3464
3465std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3466 std::string Desc) {
3467 std::string S = "\nstruct " + Tag;
3468 std::string Constructor = " " + Tag;
3469
3470 S += " {\n struct __block_impl impl;\n";
3471 S += " struct " + Desc;
3472 S += "* Desc;\n";
3473
3474 Constructor += "(void *fp, "; // Invoke function pointer.
3475 Constructor += "struct " + Desc; // Descriptor pointer.
3476 Constructor += " *desc";
3477
3478 if (BlockDeclRefs.size()) {
3479 // Output all "by copy" declarations.
3480 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3481 E = BlockByCopyDecls.end(); I != E; ++I) {
3482 S += " ";
3483 std::string FieldName = (*I)->getNameAsString();
3484 std::string ArgName = "_" + FieldName;
3485 // Handle nested closure invocation. For example:
3486 //
3487 // void (^myImportedBlock)(void);
3488 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3489 //
3490 // void (^anotherBlock)(void);
3491 // anotherBlock = ^(void) {
3492 // myImportedBlock(); // import and invoke the closure
3493 // };
3494 //
3495 if (isTopLevelBlockPointerType((*I)->getType())) {
3496 S += "struct __block_impl *";
3497 Constructor += ", void *" + ArgName;
3498 } else {
3499 QualType QT = (*I)->getType();
3500 if (HasLocalVariableExternalStorage(*I))
3501 QT = Context->getPointerType(QT);
3502 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3503 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3504 Constructor += ", " + ArgName;
3505 }
3506 S += FieldName + ";\n";
3507 }
3508 // Output all "by ref" declarations.
3509 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3510 E = BlockByRefDecls.end(); I != E; ++I) {
3511 S += " ";
3512 std::string FieldName = (*I)->getNameAsString();
3513 std::string ArgName = "_" + FieldName;
3514 {
3515 std::string TypeString;
3516 RewriteByRefString(TypeString, FieldName, (*I));
3517 TypeString += " *";
3518 FieldName = TypeString + FieldName;
3519 ArgName = TypeString + ArgName;
3520 Constructor += ", " + ArgName;
3521 }
3522 S += FieldName + "; // by ref\n";
3523 }
3524 // Finish writing the constructor.
3525 Constructor += ", int flags=0)";
3526 // Initialize all "by copy" arguments.
3527 bool firsTime = true;
3528 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3529 E = BlockByCopyDecls.end(); I != E; ++I) {
3530 std::string Name = (*I)->getNameAsString();
3531 if (firsTime) {
3532 Constructor += " : ";
3533 firsTime = false;
3534 }
3535 else
3536 Constructor += ", ";
3537 if (isTopLevelBlockPointerType((*I)->getType()))
3538 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3539 else
3540 Constructor += Name + "(_" + Name + ")";
3541 }
3542 // Initialize all "by ref" arguments.
3543 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3544 E = BlockByRefDecls.end(); I != E; ++I) {
3545 std::string Name = (*I)->getNameAsString();
3546 if (firsTime) {
3547 Constructor += " : ";
3548 firsTime = false;
3549 }
3550 else
3551 Constructor += ", ";
3552 Constructor += Name + "(_" + Name + "->__forwarding)";
3553 }
3554
3555 Constructor += " {\n";
3556 if (GlobalVarDecl)
3557 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3558 else
3559 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3560 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3561
3562 Constructor += " Desc = desc;\n";
3563 } else {
3564 // Finish writing the constructor.
3565 Constructor += ", int flags=0) {\n";
3566 if (GlobalVarDecl)
3567 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3568 else
3569 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3570 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3571 Constructor += " Desc = desc;\n";
3572 }
3573 Constructor += " ";
3574 Constructor += "}\n";
3575 S += Constructor;
3576 S += "};\n";
3577 return S;
3578}
3579
3580std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3581 std::string ImplTag, int i,
3582 StringRef FunName,
3583 unsigned hasCopy) {
3584 std::string S = "\nstatic struct " + DescTag;
3585
3586 S += " {\n unsigned long reserved;\n";
3587 S += " unsigned long Block_size;\n";
3588 if (hasCopy) {
3589 S += " void (*copy)(struct ";
3590 S += ImplTag; S += "*, struct ";
3591 S += ImplTag; S += "*);\n";
3592
3593 S += " void (*dispose)(struct ";
3594 S += ImplTag; S += "*);\n";
3595 }
3596 S += "} ";
3597
3598 S += DescTag + "_DATA = { 0, sizeof(struct ";
3599 S += ImplTag + ")";
3600 if (hasCopy) {
3601 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3602 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3603 }
3604 S += "};\n";
3605 return S;
3606}
3607
3608void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3609 StringRef FunName) {
3610 // Insert declaration for the function in which block literal is used.
3611 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3612 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3613 bool RewriteSC = (GlobalVarDecl &&
3614 !Blocks.empty() &&
3615 GlobalVarDecl->getStorageClass() == SC_Static &&
3616 GlobalVarDecl->getType().getCVRQualifiers());
3617 if (RewriteSC) {
3618 std::string SC(" void __");
3619 SC += GlobalVarDecl->getNameAsString();
3620 SC += "() {}";
3621 InsertText(FunLocStart, SC);
3622 }
3623
3624 // Insert closures that were part of the function.
3625 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3626 CollectBlockDeclRefInfo(Blocks[i]);
3627 // Need to copy-in the inner copied-in variables not actually used in this
3628 // block.
3629 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003630 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003631 ValueDecl *VD = Exp->getDecl();
3632 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003633 if (!VD->hasAttr<BlocksAttr>()) {
3634 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3635 BlockByCopyDeclsPtrSet.insert(VD);
3636 BlockByCopyDecls.push_back(VD);
3637 }
3638 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003639 }
John McCallf4b88a42012-03-10 09:33:50 +00003640
3641 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003642 BlockByRefDeclsPtrSet.insert(VD);
3643 BlockByRefDecls.push_back(VD);
3644 }
John McCallf4b88a42012-03-10 09:33:50 +00003645
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003646 // imported objects in the inner blocks not used in the outer
3647 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003648 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003649 VD->getType()->isBlockPointerType())
3650 ImportedBlockDecls.insert(VD);
3651 }
3652
3653 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3654 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3655
3656 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3657
3658 InsertText(FunLocStart, CI);
3659
3660 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3661
3662 InsertText(FunLocStart, CF);
3663
3664 if (ImportedBlockDecls.size()) {
3665 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3666 InsertText(FunLocStart, HF);
3667 }
3668 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3669 ImportedBlockDecls.size() > 0);
3670 InsertText(FunLocStart, BD);
3671
3672 BlockDeclRefs.clear();
3673 BlockByRefDecls.clear();
3674 BlockByRefDeclsPtrSet.clear();
3675 BlockByCopyDecls.clear();
3676 BlockByCopyDeclsPtrSet.clear();
3677 ImportedBlockDecls.clear();
3678 }
3679 if (RewriteSC) {
3680 // Must insert any 'const/volatile/static here. Since it has been
3681 // removed as result of rewriting of block literals.
3682 std::string SC;
3683 if (GlobalVarDecl->getStorageClass() == SC_Static)
3684 SC = "static ";
3685 if (GlobalVarDecl->getType().isConstQualified())
3686 SC += "const ";
3687 if (GlobalVarDecl->getType().isVolatileQualified())
3688 SC += "volatile ";
3689 if (GlobalVarDecl->getType().isRestrictQualified())
3690 SC += "restrict ";
3691 InsertText(FunLocStart, SC);
3692 }
3693
3694 Blocks.clear();
3695 InnerDeclRefsCount.clear();
3696 InnerDeclRefs.clear();
3697 RewrittenBlockExprs.clear();
3698}
3699
3700void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3701 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3702 StringRef FuncName = FD->getName();
3703
3704 SynthesizeBlockLiterals(FunLocStart, FuncName);
3705}
3706
3707static void BuildUniqueMethodName(std::string &Name,
3708 ObjCMethodDecl *MD) {
3709 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3710 Name = IFace->getName();
3711 Name += "__" + MD->getSelector().getAsString();
3712 // Convert colons to underscores.
3713 std::string::size_type loc = 0;
3714 while ((loc = Name.find(":", loc)) != std::string::npos)
3715 Name.replace(loc, 1, "_");
3716}
3717
3718void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3719 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3720 //SourceLocation FunLocStart = MD->getLocStart();
3721 SourceLocation FunLocStart = MD->getLocStart();
3722 std::string FuncName;
3723 BuildUniqueMethodName(FuncName, MD);
3724 SynthesizeBlockLiterals(FunLocStart, FuncName);
3725}
3726
3727void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3728 for (Stmt::child_range CI = S->children(); CI; ++CI)
3729 if (*CI) {
3730 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3731 GetBlockDeclRefExprs(CBE->getBody());
3732 else
3733 GetBlockDeclRefExprs(*CI);
3734 }
3735 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3737 if (DRE->refersToEnclosingLocal() &&
3738 HasLocalVariableExternalStorage(DRE->getDecl())) {
3739 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003740 }
3741
3742 return;
3743}
3744
3745void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003746 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003747 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3748 for (Stmt::child_range CI = S->children(); CI; ++CI)
3749 if (*CI) {
3750 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3751 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3752 GetInnerBlockDeclRefExprs(CBE->getBody(),
3753 InnerBlockDeclRefs,
3754 InnerContexts);
3755 }
3756 else
3757 GetInnerBlockDeclRefExprs(*CI,
3758 InnerBlockDeclRefs,
3759 InnerContexts);
3760
3761 }
3762 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003763 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3764 if (DRE->refersToEnclosingLocal()) {
3765 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3766 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3767 InnerBlockDeclRefs.push_back(DRE);
3768 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3769 if (Var->isFunctionOrMethodVarDecl())
3770 ImportedLocalExternalDecls.insert(Var);
3771 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003772 }
3773
3774 return;
3775}
3776
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003777/// convertObjCTypeToCStyleType - This routine converts such objc types
3778/// as qualified objects, and blocks to their closest c/c++ types that
3779/// it can. It returns true if input type was modified.
3780bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3781 QualType oldT = T;
3782 convertBlockPointerToFunctionPointer(T);
3783 if (T->isFunctionPointerType()) {
3784 QualType PointeeTy;
3785 if (const PointerType* PT = T->getAs<PointerType>()) {
3786 PointeeTy = PT->getPointeeType();
3787 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3788 T = convertFunctionTypeOfBlocks(FT);
3789 T = Context->getPointerType(T);
3790 }
3791 }
3792 }
3793
3794 convertToUnqualifiedObjCType(T);
3795 return T != oldT;
3796}
3797
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003798/// convertFunctionTypeOfBlocks - This routine converts a function type
3799/// whose result type may be a block pointer or whose argument type(s)
3800/// might be block pointers to an equivalent function type replacing
3801/// all block pointers to function pointers.
3802QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3803 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3804 // FTP will be null for closures that don't take arguments.
3805 // Generate a funky cast.
3806 SmallVector<QualType, 8> ArgTypes;
3807 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003808 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003809
3810 if (FTP) {
3811 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3812 E = FTP->arg_type_end(); I && (I != E); ++I) {
3813 QualType t = *I;
3814 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003815 if (convertObjCTypeToCStyleType(t))
3816 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003817 ArgTypes.push_back(t);
3818 }
3819 }
3820 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003821 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003822 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3823 else FuncType = QualType(FT, 0);
3824 return FuncType;
3825}
3826
3827Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3828 // Navigate to relevant type information.
3829 const BlockPointerType *CPT = 0;
3830
3831 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3832 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003833 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3834 CPT = MExpr->getType()->getAs<BlockPointerType>();
3835 }
3836 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3837 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3838 }
3839 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3840 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3841 else if (const ConditionalOperator *CEXPR =
3842 dyn_cast<ConditionalOperator>(BlockExp)) {
3843 Expr *LHSExp = CEXPR->getLHS();
3844 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3845 Expr *RHSExp = CEXPR->getRHS();
3846 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3847 Expr *CONDExp = CEXPR->getCond();
3848 ConditionalOperator *CondExpr =
3849 new (Context) ConditionalOperator(CONDExp,
3850 SourceLocation(), cast<Expr>(LHSStmt),
3851 SourceLocation(), cast<Expr>(RHSStmt),
3852 Exp->getType(), VK_RValue, OK_Ordinary);
3853 return CondExpr;
3854 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3855 CPT = IRE->getType()->getAs<BlockPointerType>();
3856 } else if (const PseudoObjectExpr *POE
3857 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3858 CPT = POE->getType()->castAs<BlockPointerType>();
3859 } else {
3860 assert(1 && "RewriteBlockClass: Bad type");
3861 }
3862 assert(CPT && "RewriteBlockClass: Bad type");
3863 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3864 assert(FT && "RewriteBlockClass: Bad type");
3865 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3866 // FTP will be null for closures that don't take arguments.
3867
3868 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3869 SourceLocation(), SourceLocation(),
3870 &Context->Idents.get("__block_impl"));
3871 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3872
3873 // Generate a funky cast.
3874 SmallVector<QualType, 8> ArgTypes;
3875
3876 // Push the block argument type.
3877 ArgTypes.push_back(PtrBlock);
3878 if (FTP) {
3879 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3880 E = FTP->arg_type_end(); I && (I != E); ++I) {
3881 QualType t = *I;
3882 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3883 if (!convertBlockPointerToFunctionPointer(t))
3884 convertToUnqualifiedObjCType(t);
3885 ArgTypes.push_back(t);
3886 }
3887 }
3888 // Now do the pointer to function cast.
3889 QualType PtrToFuncCastType
3890 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3891
3892 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3893
3894 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3895 CK_BitCast,
3896 const_cast<Expr*>(BlockExp));
3897 // Don't forget the parens to enforce the proper binding.
3898 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3899 BlkCast);
3900 //PE->dump();
3901
3902 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3903 SourceLocation(),
3904 &Context->Idents.get("FuncPtr"),
3905 Context->VoidPtrTy, 0,
3906 /*BitWidth=*/0, /*Mutable=*/true,
3907 /*HasInit=*/false);
3908 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3909 FD->getType(), VK_LValue,
3910 OK_Ordinary);
3911
3912
3913 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3914 CK_BitCast, ME);
3915 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3916
3917 SmallVector<Expr*, 8> BlkExprs;
3918 // Add the implicit argument.
3919 BlkExprs.push_back(BlkCast);
3920 // Add the user arguments.
3921 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3922 E = Exp->arg_end(); I != E; ++I) {
3923 BlkExprs.push_back(*I);
3924 }
3925 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3926 BlkExprs.size(),
3927 Exp->getType(), VK_RValue,
3928 SourceLocation());
3929 return CE;
3930}
3931
3932// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003933// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003934// For example:
3935//
3936// int main() {
3937// __block Foo *f;
3938// __block int i;
3939//
3940// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003941// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003942// i = 77;
3943// };
3944//}
John McCallf4b88a42012-03-10 09:33:50 +00003945Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003946 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3947 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003948 ValueDecl *VD = DeclRefExp->getDecl();
3949 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003950
3951 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3952 SourceLocation(),
3953 &Context->Idents.get("__forwarding"),
3954 Context->VoidPtrTy, 0,
3955 /*BitWidth=*/0, /*Mutable=*/true,
3956 /*HasInit=*/false);
3957 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3958 FD, SourceLocation(),
3959 FD->getType(), VK_LValue,
3960 OK_Ordinary);
3961
3962 StringRef Name = VD->getName();
3963 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3964 &Context->Idents.get(Name),
3965 Context->VoidPtrTy, 0,
3966 /*BitWidth=*/0, /*Mutable=*/true,
3967 /*HasInit=*/false);
3968 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3969 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3970
3971
3972
3973 // Need parens to enforce precedence.
3974 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3975 DeclRefExp->getExprLoc(),
3976 ME);
3977 ReplaceStmt(DeclRefExp, PE);
3978 return PE;
3979}
3980
3981// Rewrites the imported local variable V with external storage
3982// (static, extern, etc.) as *V
3983//
3984Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3985 ValueDecl *VD = DRE->getDecl();
3986 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3987 if (!ImportedLocalExternalDecls.count(Var))
3988 return DRE;
3989 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3990 VK_LValue, OK_Ordinary,
3991 DRE->getLocation());
3992 // Need parens to enforce precedence.
3993 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3994 Exp);
3995 ReplaceStmt(DRE, PE);
3996 return PE;
3997}
3998
3999void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4000 SourceLocation LocStart = CE->getLParenLoc();
4001 SourceLocation LocEnd = CE->getRParenLoc();
4002
4003 // Need to avoid trying to rewrite synthesized casts.
4004 if (LocStart.isInvalid())
4005 return;
4006 // Need to avoid trying to rewrite casts contained in macros.
4007 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4008 return;
4009
4010 const char *startBuf = SM->getCharacterData(LocStart);
4011 const char *endBuf = SM->getCharacterData(LocEnd);
4012 QualType QT = CE->getType();
4013 const Type* TypePtr = QT->getAs<Type>();
4014 if (isa<TypeOfExprType>(TypePtr)) {
4015 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4016 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4017 std::string TypeAsString = "(";
4018 RewriteBlockPointerType(TypeAsString, QT);
4019 TypeAsString += ")";
4020 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4021 return;
4022 }
4023 // advance the location to startArgList.
4024 const char *argPtr = startBuf;
4025
4026 while (*argPtr++ && (argPtr < endBuf)) {
4027 switch (*argPtr) {
4028 case '^':
4029 // Replace the '^' with '*'.
4030 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4031 ReplaceText(LocStart, 1, "*");
4032 break;
4033 }
4034 }
4035 return;
4036}
4037
4038void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4039 SourceLocation DeclLoc = FD->getLocation();
4040 unsigned parenCount = 0;
4041
4042 // We have 1 or more arguments that have closure pointers.
4043 const char *startBuf = SM->getCharacterData(DeclLoc);
4044 const char *startArgList = strchr(startBuf, '(');
4045
4046 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4047
4048 parenCount++;
4049 // advance the location to startArgList.
4050 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4051 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4052
4053 const char *argPtr = startArgList;
4054
4055 while (*argPtr++ && parenCount) {
4056 switch (*argPtr) {
4057 case '^':
4058 // Replace the '^' with '*'.
4059 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4060 ReplaceText(DeclLoc, 1, "*");
4061 break;
4062 case '(':
4063 parenCount++;
4064 break;
4065 case ')':
4066 parenCount--;
4067 break;
4068 }
4069 }
4070 return;
4071}
4072
4073bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4074 const FunctionProtoType *FTP;
4075 const PointerType *PT = QT->getAs<PointerType>();
4076 if (PT) {
4077 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4078 } else {
4079 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4080 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4081 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4082 }
4083 if (FTP) {
4084 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4085 E = FTP->arg_type_end(); I != E; ++I)
4086 if (isTopLevelBlockPointerType(*I))
4087 return true;
4088 }
4089 return false;
4090}
4091
4092bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4093 const FunctionProtoType *FTP;
4094 const PointerType *PT = QT->getAs<PointerType>();
4095 if (PT) {
4096 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4097 } else {
4098 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4099 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4100 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4101 }
4102 if (FTP) {
4103 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4104 E = FTP->arg_type_end(); I != E; ++I) {
4105 if ((*I)->isObjCQualifiedIdType())
4106 return true;
4107 if ((*I)->isObjCObjectPointerType() &&
4108 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4109 return true;
4110 }
4111
4112 }
4113 return false;
4114}
4115
4116void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4117 const char *&RParen) {
4118 const char *argPtr = strchr(Name, '(');
4119 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4120
4121 LParen = argPtr; // output the start.
4122 argPtr++; // skip past the left paren.
4123 unsigned parenCount = 1;
4124
4125 while (*argPtr && parenCount) {
4126 switch (*argPtr) {
4127 case '(': parenCount++; break;
4128 case ')': parenCount--; break;
4129 default: break;
4130 }
4131 if (parenCount) argPtr++;
4132 }
4133 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4134 RParen = argPtr; // output the end
4135}
4136
4137void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4138 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4139 RewriteBlockPointerFunctionArgs(FD);
4140 return;
4141 }
4142 // Handle Variables and Typedefs.
4143 SourceLocation DeclLoc = ND->getLocation();
4144 QualType DeclT;
4145 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4146 DeclT = VD->getType();
4147 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4148 DeclT = TDD->getUnderlyingType();
4149 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4150 DeclT = FD->getType();
4151 else
4152 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4153
4154 const char *startBuf = SM->getCharacterData(DeclLoc);
4155 const char *endBuf = startBuf;
4156 // scan backward (from the decl location) for the end of the previous decl.
4157 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4158 startBuf--;
4159 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4160 std::string buf;
4161 unsigned OrigLength=0;
4162 // *startBuf != '^' if we are dealing with a pointer to function that
4163 // may take block argument types (which will be handled below).
4164 if (*startBuf == '^') {
4165 // Replace the '^' with '*', computing a negative offset.
4166 buf = '*';
4167 startBuf++;
4168 OrigLength++;
4169 }
4170 while (*startBuf != ')') {
4171 buf += *startBuf;
4172 startBuf++;
4173 OrigLength++;
4174 }
4175 buf += ')';
4176 OrigLength++;
4177
4178 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4179 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4180 // Replace the '^' with '*' for arguments.
4181 // Replace id<P> with id/*<>*/
4182 DeclLoc = ND->getLocation();
4183 startBuf = SM->getCharacterData(DeclLoc);
4184 const char *argListBegin, *argListEnd;
4185 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4186 while (argListBegin < argListEnd) {
4187 if (*argListBegin == '^')
4188 buf += '*';
4189 else if (*argListBegin == '<') {
4190 buf += "/*";
4191 buf += *argListBegin++;
4192 OrigLength++;;
4193 while (*argListBegin != '>') {
4194 buf += *argListBegin++;
4195 OrigLength++;
4196 }
4197 buf += *argListBegin;
4198 buf += "*/";
4199 }
4200 else
4201 buf += *argListBegin;
4202 argListBegin++;
4203 OrigLength++;
4204 }
4205 buf += ')';
4206 OrigLength++;
4207 }
4208 ReplaceText(Start, OrigLength, buf);
4209
4210 return;
4211}
4212
4213
4214/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4215/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4216/// struct Block_byref_id_object *src) {
4217/// _Block_object_assign (&_dest->object, _src->object,
4218/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4219/// [|BLOCK_FIELD_IS_WEAK]) // object
4220/// _Block_object_assign(&_dest->object, _src->object,
4221/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4222/// [|BLOCK_FIELD_IS_WEAK]) // block
4223/// }
4224/// And:
4225/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4226/// _Block_object_dispose(_src->object,
4227/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4228/// [|BLOCK_FIELD_IS_WEAK]) // object
4229/// _Block_object_dispose(_src->object,
4230/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4231/// [|BLOCK_FIELD_IS_WEAK]) // block
4232/// }
4233
4234std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4235 int flag) {
4236 std::string S;
4237 if (CopyDestroyCache.count(flag))
4238 return S;
4239 CopyDestroyCache.insert(flag);
4240 S = "static void __Block_byref_id_object_copy_";
4241 S += utostr(flag);
4242 S += "(void *dst, void *src) {\n";
4243
4244 // offset into the object pointer is computed as:
4245 // void * + void* + int + int + void* + void *
4246 unsigned IntSize =
4247 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4248 unsigned VoidPtrSize =
4249 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4250
4251 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4252 S += " _Block_object_assign((char*)dst + ";
4253 S += utostr(offset);
4254 S += ", *(void * *) ((char*)src + ";
4255 S += utostr(offset);
4256 S += "), ";
4257 S += utostr(flag);
4258 S += ");\n}\n";
4259
4260 S += "static void __Block_byref_id_object_dispose_";
4261 S += utostr(flag);
4262 S += "(void *src) {\n";
4263 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4264 S += utostr(offset);
4265 S += "), ";
4266 S += utostr(flag);
4267 S += ");\n}\n";
4268 return S;
4269}
4270
4271/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4272/// the declaration into:
4273/// struct __Block_byref_ND {
4274/// void *__isa; // NULL for everything except __weak pointers
4275/// struct __Block_byref_ND *__forwarding;
4276/// int32_t __flags;
4277/// int32_t __size;
4278/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4279/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4280/// typex ND;
4281/// };
4282///
4283/// It then replaces declaration of ND variable with:
4284/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4285/// __size=sizeof(struct __Block_byref_ND),
4286/// ND=initializer-if-any};
4287///
4288///
4289void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4290 // Insert declaration for the function in which block literal is
4291 // used.
4292 if (CurFunctionDeclToDeclareForBlock)
4293 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4294 int flag = 0;
4295 int isa = 0;
4296 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4297 if (DeclLoc.isInvalid())
4298 // If type location is missing, it is because of missing type (a warning).
4299 // Use variable's location which is good for this case.
4300 DeclLoc = ND->getLocation();
4301 const char *startBuf = SM->getCharacterData(DeclLoc);
4302 SourceLocation X = ND->getLocEnd();
4303 X = SM->getExpansionLoc(X);
4304 const char *endBuf = SM->getCharacterData(X);
4305 std::string Name(ND->getNameAsString());
4306 std::string ByrefType;
4307 RewriteByRefString(ByrefType, Name, ND, true);
4308 ByrefType += " {\n";
4309 ByrefType += " void *__isa;\n";
4310 RewriteByRefString(ByrefType, Name, ND);
4311 ByrefType += " *__forwarding;\n";
4312 ByrefType += " int __flags;\n";
4313 ByrefType += " int __size;\n";
4314 // Add void *__Block_byref_id_object_copy;
4315 // void *__Block_byref_id_object_dispose; if needed.
4316 QualType Ty = ND->getType();
4317 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4318 if (HasCopyAndDispose) {
4319 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4320 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4321 }
4322
4323 QualType T = Ty;
4324 (void)convertBlockPointerToFunctionPointer(T);
4325 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4326
4327 ByrefType += " " + Name + ";\n";
4328 ByrefType += "};\n";
4329 // Insert this type in global scope. It is needed by helper function.
4330 SourceLocation FunLocStart;
4331 if (CurFunctionDef)
4332 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4333 else {
4334 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4335 FunLocStart = CurMethodDef->getLocStart();
4336 }
4337 InsertText(FunLocStart, ByrefType);
4338 if (Ty.isObjCGCWeak()) {
4339 flag |= BLOCK_FIELD_IS_WEAK;
4340 isa = 1;
4341 }
4342
4343 if (HasCopyAndDispose) {
4344 flag = BLOCK_BYREF_CALLER;
4345 QualType Ty = ND->getType();
4346 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4347 if (Ty->isBlockPointerType())
4348 flag |= BLOCK_FIELD_IS_BLOCK;
4349 else
4350 flag |= BLOCK_FIELD_IS_OBJECT;
4351 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4352 if (!HF.empty())
4353 InsertText(FunLocStart, HF);
4354 }
4355
4356 // struct __Block_byref_ND ND =
4357 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4358 // initializer-if-any};
4359 bool hasInit = (ND->getInit() != 0);
4360 unsigned flags = 0;
4361 if (HasCopyAndDispose)
4362 flags |= BLOCK_HAS_COPY_DISPOSE;
4363 Name = ND->getNameAsString();
4364 ByrefType.clear();
4365 RewriteByRefString(ByrefType, Name, ND);
4366 std::string ForwardingCastType("(");
4367 ForwardingCastType += ByrefType + " *)";
4368 if (!hasInit) {
4369 ByrefType += " " + Name + " = {(void*)";
4370 ByrefType += utostr(isa);
4371 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4372 ByrefType += utostr(flags);
4373 ByrefType += ", ";
4374 ByrefType += "sizeof(";
4375 RewriteByRefString(ByrefType, Name, ND);
4376 ByrefType += ")";
4377 if (HasCopyAndDispose) {
4378 ByrefType += ", __Block_byref_id_object_copy_";
4379 ByrefType += utostr(flag);
4380 ByrefType += ", __Block_byref_id_object_dispose_";
4381 ByrefType += utostr(flag);
4382 }
4383 ByrefType += "};\n";
4384 unsigned nameSize = Name.size();
4385 // for block or function pointer declaration. Name is aleady
4386 // part of the declaration.
4387 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4388 nameSize = 1;
4389 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4390 }
4391 else {
4392 SourceLocation startLoc;
4393 Expr *E = ND->getInit();
4394 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4395 startLoc = ECE->getLParenLoc();
4396 else
4397 startLoc = E->getLocStart();
4398 startLoc = SM->getExpansionLoc(startLoc);
4399 endBuf = SM->getCharacterData(startLoc);
4400 ByrefType += " " + Name;
4401 ByrefType += " = {(void*)";
4402 ByrefType += utostr(isa);
4403 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4404 ByrefType += utostr(flags);
4405 ByrefType += ", ";
4406 ByrefType += "sizeof(";
4407 RewriteByRefString(ByrefType, Name, ND);
4408 ByrefType += "), ";
4409 if (HasCopyAndDispose) {
4410 ByrefType += "__Block_byref_id_object_copy_";
4411 ByrefType += utostr(flag);
4412 ByrefType += ", __Block_byref_id_object_dispose_";
4413 ByrefType += utostr(flag);
4414 ByrefType += ", ";
4415 }
4416 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4417
4418 // Complete the newly synthesized compound expression by inserting a right
4419 // curly brace before the end of the declaration.
4420 // FIXME: This approach avoids rewriting the initializer expression. It
4421 // also assumes there is only one declarator. For example, the following
4422 // isn't currently supported by this routine (in general):
4423 //
4424 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4425 //
4426 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4427 const char *semiBuf = strchr(startInitializerBuf, ';');
4428 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4429 SourceLocation semiLoc =
4430 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4431
4432 InsertText(semiLoc, "}");
4433 }
4434 return;
4435}
4436
4437void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4438 // Add initializers for any closure decl refs.
4439 GetBlockDeclRefExprs(Exp->getBody());
4440 if (BlockDeclRefs.size()) {
4441 // Unique all "by copy" declarations.
4442 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004443 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004444 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4445 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4446 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4447 }
4448 }
4449 // Unique all "by ref" declarations.
4450 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004451 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004452 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4453 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4454 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4455 }
4456 }
4457 // Find any imported blocks...they will need special attention.
4458 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004459 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004460 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4461 BlockDeclRefs[i]->getType()->isBlockPointerType())
4462 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4463 }
4464}
4465
4466FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4467 IdentifierInfo *ID = &Context->Idents.get(name);
4468 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4469 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4470 SourceLocation(), ID, FType, 0, SC_Extern,
4471 SC_None, false, false);
4472}
4473
4474Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004475 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004476 const BlockDecl *block = Exp->getBlockDecl();
4477 Blocks.push_back(Exp);
4478
4479 CollectBlockDeclRefInfo(Exp);
4480
4481 // Add inner imported variables now used in current block.
4482 int countOfInnerDecls = 0;
4483 if (!InnerBlockDeclRefs.empty()) {
4484 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004485 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004486 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004487 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004488 // We need to save the copied-in variables in nested
4489 // blocks because it is needed at the end for some of the API generations.
4490 // See SynthesizeBlockLiterals routine.
4491 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4492 BlockDeclRefs.push_back(Exp);
4493 BlockByCopyDeclsPtrSet.insert(VD);
4494 BlockByCopyDecls.push_back(VD);
4495 }
John McCallf4b88a42012-03-10 09:33:50 +00004496 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004497 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4498 BlockDeclRefs.push_back(Exp);
4499 BlockByRefDeclsPtrSet.insert(VD);
4500 BlockByRefDecls.push_back(VD);
4501 }
4502 }
4503 // Find any imported blocks...they will need special attention.
4504 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004505 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004506 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4507 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4508 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4509 }
4510 InnerDeclRefsCount.push_back(countOfInnerDecls);
4511
4512 std::string FuncName;
4513
4514 if (CurFunctionDef)
4515 FuncName = CurFunctionDef->getNameAsString();
4516 else if (CurMethodDef)
4517 BuildUniqueMethodName(FuncName, CurMethodDef);
4518 else if (GlobalVarDecl)
4519 FuncName = std::string(GlobalVarDecl->getNameAsString());
4520
4521 std::string BlockNumber = utostr(Blocks.size()-1);
4522
4523 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4524 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4525
4526 // Get a pointer to the function type so we can cast appropriately.
4527 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4528 QualType FType = Context->getPointerType(BFT);
4529
4530 FunctionDecl *FD;
4531 Expr *NewRep;
4532
4533 // Simulate a contructor call...
4534 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004535 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004536 SourceLocation());
4537
4538 SmallVector<Expr*, 4> InitExprs;
4539
4540 // Initialize the block function.
4541 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004542 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4543 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004544 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4545 CK_BitCast, Arg);
4546 InitExprs.push_back(castExpr);
4547
4548 // Initialize the block descriptor.
4549 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4550
4551 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4552 SourceLocation(), SourceLocation(),
4553 &Context->Idents.get(DescData.c_str()),
4554 Context->VoidPtrTy, 0,
4555 SC_Static, SC_None);
4556 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004557 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004558 Context->VoidPtrTy,
4559 VK_LValue,
4560 SourceLocation()),
4561 UO_AddrOf,
4562 Context->getPointerType(Context->VoidPtrTy),
4563 VK_RValue, OK_Ordinary,
4564 SourceLocation());
4565 InitExprs.push_back(DescRefExpr);
4566
4567 // Add initializers for any closure decl refs.
4568 if (BlockDeclRefs.size()) {
4569 Expr *Exp;
4570 // Output all "by copy" declarations.
4571 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4572 E = BlockByCopyDecls.end(); I != E; ++I) {
4573 if (isObjCType((*I)->getType())) {
4574 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4575 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004576 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4577 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004578 if (HasLocalVariableExternalStorage(*I)) {
4579 QualType QT = (*I)->getType();
4580 QT = Context->getPointerType(QT);
4581 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4582 OK_Ordinary, SourceLocation());
4583 }
4584 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4585 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004586 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4587 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004588 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4589 CK_BitCast, Arg);
4590 } else {
4591 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004592 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4593 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004594 if (HasLocalVariableExternalStorage(*I)) {
4595 QualType QT = (*I)->getType();
4596 QT = Context->getPointerType(QT);
4597 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4598 OK_Ordinary, SourceLocation());
4599 }
4600
4601 }
4602 InitExprs.push_back(Exp);
4603 }
4604 // Output all "by ref" declarations.
4605 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4606 E = BlockByRefDecls.end(); I != E; ++I) {
4607 ValueDecl *ND = (*I);
4608 std::string Name(ND->getNameAsString());
4609 std::string RecName;
4610 RewriteByRefString(RecName, Name, ND, true);
4611 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4612 + sizeof("struct"));
4613 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4614 SourceLocation(), SourceLocation(),
4615 II);
4616 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4617 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4618
4619 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004620 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004621 SourceLocation());
4622 bool isNestedCapturedVar = false;
4623 if (block)
4624 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4625 ce = block->capture_end(); ci != ce; ++ci) {
4626 const VarDecl *variable = ci->getVariable();
4627 if (variable == ND && ci->isNested()) {
4628 assert (ci->isByRef() &&
4629 "SynthBlockInitExpr - captured block variable is not byref");
4630 isNestedCapturedVar = true;
4631 break;
4632 }
4633 }
4634 // captured nested byref variable has its address passed. Do not take
4635 // its address again.
4636 if (!isNestedCapturedVar)
4637 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4638 Context->getPointerType(Exp->getType()),
4639 VK_RValue, OK_Ordinary, SourceLocation());
4640 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4641 InitExprs.push_back(Exp);
4642 }
4643 }
4644 if (ImportedBlockDecls.size()) {
4645 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4646 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4647 unsigned IntSize =
4648 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4649 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4650 Context->IntTy, SourceLocation());
4651 InitExprs.push_back(FlagExp);
4652 }
4653 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4654 FType, VK_LValue, SourceLocation());
4655 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4656 Context->getPointerType(NewRep->getType()),
4657 VK_RValue, OK_Ordinary, SourceLocation());
4658 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4659 NewRep);
4660 BlockDeclRefs.clear();
4661 BlockByRefDecls.clear();
4662 BlockByRefDeclsPtrSet.clear();
4663 BlockByCopyDecls.clear();
4664 BlockByCopyDeclsPtrSet.clear();
4665 ImportedBlockDecls.clear();
4666 return NewRep;
4667}
4668
4669bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4670 if (const ObjCForCollectionStmt * CS =
4671 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4672 return CS->getElement() == DS;
4673 return false;
4674}
4675
4676//===----------------------------------------------------------------------===//
4677// Function Body / Expression rewriting
4678//===----------------------------------------------------------------------===//
4679
4680Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4681 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4682 isa<DoStmt>(S) || isa<ForStmt>(S))
4683 Stmts.push_back(S);
4684 else if (isa<ObjCForCollectionStmt>(S)) {
4685 Stmts.push_back(S);
4686 ObjCBcLabelNo.push_back(++BcLabelCount);
4687 }
4688
4689 // Pseudo-object operations and ivar references need special
4690 // treatment because we're going to recursively rewrite them.
4691 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4692 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4693 return RewritePropertyOrImplicitSetter(PseudoOp);
4694 } else {
4695 return RewritePropertyOrImplicitGetter(PseudoOp);
4696 }
4697 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4698 return RewriteObjCIvarRefExpr(IvarRefExpr);
4699 }
4700
4701 SourceRange OrigStmtRange = S->getSourceRange();
4702
4703 // Perform a bottom up rewrite of all children.
4704 for (Stmt::child_range CI = S->children(); CI; ++CI)
4705 if (*CI) {
4706 Stmt *childStmt = (*CI);
4707 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4708 if (newStmt) {
4709 *CI = newStmt;
4710 }
4711 }
4712
4713 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004714 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004715 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4716 InnerContexts.insert(BE->getBlockDecl());
4717 ImportedLocalExternalDecls.clear();
4718 GetInnerBlockDeclRefExprs(BE->getBody(),
4719 InnerBlockDeclRefs, InnerContexts);
4720 // Rewrite the block body in place.
4721 Stmt *SaveCurrentBody = CurrentBody;
4722 CurrentBody = BE->getBody();
4723 PropParentMap = 0;
4724 // block literal on rhs of a property-dot-sytax assignment
4725 // must be replaced by its synthesize ast so getRewrittenText
4726 // works as expected. In this case, what actually ends up on RHS
4727 // is the blockTranscribed which is the helper function for the
4728 // block literal; as in: self.c = ^() {[ace ARR];};
4729 bool saveDisableReplaceStmt = DisableReplaceStmt;
4730 DisableReplaceStmt = false;
4731 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4732 DisableReplaceStmt = saveDisableReplaceStmt;
4733 CurrentBody = SaveCurrentBody;
4734 PropParentMap = 0;
4735 ImportedLocalExternalDecls.clear();
4736 // Now we snarf the rewritten text and stash it away for later use.
4737 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4738 RewrittenBlockExprs[BE] = Str;
4739
4740 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4741
4742 //blockTranscribed->dump();
4743 ReplaceStmt(S, blockTranscribed);
4744 return blockTranscribed;
4745 }
4746 // Handle specific things.
4747 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4748 return RewriteAtEncode(AtEncode);
4749
4750 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4751 return RewriteAtSelector(AtSelector);
4752
4753 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4754 return RewriteObjCStringLiteral(AtString);
4755
4756 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4757#if 0
4758 // Before we rewrite it, put the original message expression in a comment.
4759 SourceLocation startLoc = MessExpr->getLocStart();
4760 SourceLocation endLoc = MessExpr->getLocEnd();
4761
4762 const char *startBuf = SM->getCharacterData(startLoc);
4763 const char *endBuf = SM->getCharacterData(endLoc);
4764
4765 std::string messString;
4766 messString += "// ";
4767 messString.append(startBuf, endBuf-startBuf+1);
4768 messString += "\n";
4769
4770 // FIXME: Missing definition of
4771 // InsertText(clang::SourceLocation, char const*, unsigned int).
4772 // InsertText(startLoc, messString.c_str(), messString.size());
4773 // Tried this, but it didn't work either...
4774 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4775#endif
4776 return RewriteMessageExpr(MessExpr);
4777 }
4778
4779 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4780 return RewriteObjCTryStmt(StmtTry);
4781
4782 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4783 return RewriteObjCSynchronizedStmt(StmtTry);
4784
4785 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4786 return RewriteObjCThrowStmt(StmtThrow);
4787
4788 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4789 return RewriteObjCProtocolExpr(ProtocolExp);
4790
4791 if (ObjCForCollectionStmt *StmtForCollection =
4792 dyn_cast<ObjCForCollectionStmt>(S))
4793 return RewriteObjCForCollectionStmt(StmtForCollection,
4794 OrigStmtRange.getEnd());
4795 if (BreakStmt *StmtBreakStmt =
4796 dyn_cast<BreakStmt>(S))
4797 return RewriteBreakStmt(StmtBreakStmt);
4798 if (ContinueStmt *StmtContinueStmt =
4799 dyn_cast<ContinueStmt>(S))
4800 return RewriteContinueStmt(StmtContinueStmt);
4801
4802 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4803 // and cast exprs.
4804 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4805 // FIXME: What we're doing here is modifying the type-specifier that
4806 // precedes the first Decl. In the future the DeclGroup should have
4807 // a separate type-specifier that we can rewrite.
4808 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4809 // the context of an ObjCForCollectionStmt. For example:
4810 // NSArray *someArray;
4811 // for (id <FooProtocol> index in someArray) ;
4812 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4813 // and it depends on the original text locations/positions.
4814 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4815 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4816
4817 // Blocks rewrite rules.
4818 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4819 DI != DE; ++DI) {
4820 Decl *SD = *DI;
4821 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4822 if (isTopLevelBlockPointerType(ND->getType()))
4823 RewriteBlockPointerDecl(ND);
4824 else if (ND->getType()->isFunctionPointerType())
4825 CheckFunctionPointerDecl(ND->getType(), ND);
4826 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4827 if (VD->hasAttr<BlocksAttr>()) {
4828 static unsigned uniqueByrefDeclCount = 0;
4829 assert(!BlockByRefDeclNo.count(ND) &&
4830 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4831 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4832 RewriteByRefVar(VD);
4833 }
4834 else
4835 RewriteTypeOfDecl(VD);
4836 }
4837 }
4838 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4839 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4840 RewriteBlockPointerDecl(TD);
4841 else if (TD->getUnderlyingType()->isFunctionPointerType())
4842 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4843 }
4844 }
4845 }
4846
4847 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4848 RewriteObjCQualifiedInterfaceTypes(CE);
4849
4850 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4851 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4852 assert(!Stmts.empty() && "Statement stack is empty");
4853 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4854 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4855 && "Statement stack mismatch");
4856 Stmts.pop_back();
4857 }
4858 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004859 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4860 ValueDecl *VD = DRE->getDecl();
4861 if (VD->hasAttr<BlocksAttr>())
4862 return RewriteBlockDeclRefExpr(DRE);
4863 if (HasLocalVariableExternalStorage(VD))
4864 return RewriteLocalVariableExternalStorage(DRE);
4865 }
4866
4867 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4868 if (CE->getCallee()->getType()->isBlockPointerType()) {
4869 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4870 ReplaceStmt(S, BlockCall);
4871 return BlockCall;
4872 }
4873 }
4874 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4875 RewriteCastExpr(CE);
4876 }
4877#if 0
4878 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4879 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4880 ICE->getSubExpr(),
4881 SourceLocation());
4882 // Get the new text.
4883 std::string SStr;
4884 llvm::raw_string_ostream Buf(SStr);
4885 Replacement->printPretty(Buf, *Context);
4886 const std::string &Str = Buf.str();
4887
4888 printf("CAST = %s\n", &Str[0]);
4889 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4890 delete S;
4891 return Replacement;
4892 }
4893#endif
4894 // Return this stmt unmodified.
4895 return S;
4896}
4897
4898void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4899 for (RecordDecl::field_iterator i = RD->field_begin(),
4900 e = RD->field_end(); i != e; ++i) {
4901 FieldDecl *FD = *i;
4902 if (isTopLevelBlockPointerType(FD->getType()))
4903 RewriteBlockPointerDecl(FD);
4904 if (FD->getType()->isObjCQualifiedIdType() ||
4905 FD->getType()->isObjCQualifiedInterfaceType())
4906 RewriteObjCQualifiedInterfaceTypes(FD);
4907 }
4908}
4909
4910/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4911/// main file of the input.
4912void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4913 switch (D->getKind()) {
4914 case Decl::Function: {
4915 FunctionDecl *FD = cast<FunctionDecl>(D);
4916 if (FD->isOverloadedOperator())
4917 return;
4918
4919 // Since function prototypes don't have ParmDecl's, we check the function
4920 // prototype. This enables us to rewrite function declarations and
4921 // definitions using the same code.
4922 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4923
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004924 if (!FD->isThisDeclarationADefinition())
4925 break;
4926
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004927 // FIXME: If this should support Obj-C++, support CXXTryStmt
4928 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4929 CurFunctionDef = FD;
4930 CurFunctionDeclToDeclareForBlock = FD;
4931 CurrentBody = Body;
4932 Body =
4933 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4934 FD->setBody(Body);
4935 CurrentBody = 0;
4936 if (PropParentMap) {
4937 delete PropParentMap;
4938 PropParentMap = 0;
4939 }
4940 // This synthesizes and inserts the block "impl" struct, invoke function,
4941 // and any copy/dispose helper functions.
4942 InsertBlockLiteralsWithinFunction(FD);
4943 CurFunctionDef = 0;
4944 CurFunctionDeclToDeclareForBlock = 0;
4945 }
4946 break;
4947 }
4948 case Decl::ObjCMethod: {
4949 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4950 if (CompoundStmt *Body = MD->getCompoundBody()) {
4951 CurMethodDef = MD;
4952 CurrentBody = Body;
4953 Body =
4954 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4955 MD->setBody(Body);
4956 CurrentBody = 0;
4957 if (PropParentMap) {
4958 delete PropParentMap;
4959 PropParentMap = 0;
4960 }
4961 InsertBlockLiteralsWithinMethod(MD);
4962 CurMethodDef = 0;
4963 }
4964 break;
4965 }
4966 case Decl::ObjCImplementation: {
4967 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4968 ClassImplementation.push_back(CI);
4969 break;
4970 }
4971 case Decl::ObjCCategoryImpl: {
4972 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4973 CategoryImplementation.push_back(CI);
4974 break;
4975 }
4976 case Decl::Var: {
4977 VarDecl *VD = cast<VarDecl>(D);
4978 RewriteObjCQualifiedInterfaceTypes(VD);
4979 if (isTopLevelBlockPointerType(VD->getType()))
4980 RewriteBlockPointerDecl(VD);
4981 else if (VD->getType()->isFunctionPointerType()) {
4982 CheckFunctionPointerDecl(VD->getType(), VD);
4983 if (VD->getInit()) {
4984 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4985 RewriteCastExpr(CE);
4986 }
4987 }
4988 } else if (VD->getType()->isRecordType()) {
4989 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4990 if (RD->isCompleteDefinition())
4991 RewriteRecordBody(RD);
4992 }
4993 if (VD->getInit()) {
4994 GlobalVarDecl = VD;
4995 CurrentBody = VD->getInit();
4996 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4997 CurrentBody = 0;
4998 if (PropParentMap) {
4999 delete PropParentMap;
5000 PropParentMap = 0;
5001 }
5002 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5003 GlobalVarDecl = 0;
5004
5005 // This is needed for blocks.
5006 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5007 RewriteCastExpr(CE);
5008 }
5009 }
5010 break;
5011 }
5012 case Decl::TypeAlias:
5013 case Decl::Typedef: {
5014 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5015 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5016 RewriteBlockPointerDecl(TD);
5017 else if (TD->getUnderlyingType()->isFunctionPointerType())
5018 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5019 }
5020 break;
5021 }
5022 case Decl::CXXRecord:
5023 case Decl::Record: {
5024 RecordDecl *RD = cast<RecordDecl>(D);
5025 if (RD->isCompleteDefinition())
5026 RewriteRecordBody(RD);
5027 break;
5028 }
5029 default:
5030 break;
5031 }
5032 // Nothing yet.
5033}
5034
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005035/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5036/// protocol reference symbols in the for of:
5037/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5038static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5039 ObjCProtocolDecl *PDecl,
5040 std::string &Result) {
5041 // Also output .objc_protorefs$B section and its meta-data.
5042 if (Context->getLangOpts().MicrosoftExt)
5043 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5044 Result += "struct _protocol_t *";
5045 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5046 Result += PDecl->getNameAsString();
5047 Result += " = &";
5048 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5049 Result += ";\n";
5050}
5051
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005052void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5053 if (Diags.hasErrorOccurred())
5054 return;
5055
5056 RewriteInclude();
5057
5058 // Here's a great place to add any extra declarations that may be needed.
5059 // Write out meta data for each @protocol(<expr>).
5060 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005061 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005062 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005063 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5064 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005065
5066 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005067 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5068 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5069 // Write struct declaration for the class matching its ivar declarations.
5070 // Note that for modern abi, this is postponed until the end of TU
5071 // because class extensions and the implementation might declare their own
5072 // private ivars.
5073 RewriteInterfaceDecl(CDecl);
5074 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005075
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005076 if (ClassImplementation.size() || CategoryImplementation.size())
5077 RewriteImplementations();
5078
5079 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5080 // we are done.
5081 if (const RewriteBuffer *RewriteBuf =
5082 Rewrite.getRewriteBufferFor(MainFileID)) {
5083 //printf("Changed:\n");
5084 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5085 } else {
5086 llvm::errs() << "No changes\n";
5087 }
5088
5089 if (ClassImplementation.size() || CategoryImplementation.size() ||
5090 ProtocolExprDecls.size()) {
5091 // Rewrite Objective-c meta data*
5092 std::string ResultStr;
5093 RewriteMetaDataIntoBuffer(ResultStr);
5094 // Emit metadata.
5095 *OutFile << ResultStr;
5096 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005097 // Emit ImageInfo;
5098 {
5099 std::string ResultStr;
5100 WriteImageInfo(ResultStr);
5101 *OutFile << ResultStr;
5102 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005103 OutFile->flush();
5104}
5105
5106void RewriteModernObjC::Initialize(ASTContext &context) {
5107 InitializeCommon(context);
5108
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005109 Preamble += "#ifndef __OBJC2__\n";
5110 Preamble += "#define __OBJC2__\n";
5111 Preamble += "#endif\n";
5112
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005113 // declaring objc_selector outside the parameter list removes a silly
5114 // scope related warning...
5115 if (IsHeader)
5116 Preamble = "#pragma once\n";
5117 Preamble += "struct objc_selector; struct objc_class;\n";
5118 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5119 Preamble += "struct objc_object *superClass; ";
5120 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005121 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005122 // These are currently generated.
5123 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005124 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005125 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5126 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005127 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5128 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005129 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005130 // These are generated but not necessary for functionality.
5131 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5132 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005133 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5134 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005135 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005136
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005137 // These need be generated for performance. Currently they are not,
5138 // using API calls instead.
5139 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5140 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5141 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5142
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005143 // Add a constructor for creating temporary objects.
5144 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5145 ": ";
5146 Preamble += "object(o), superClass(s) {} ";
5147 }
5148 Preamble += "};\n";
5149 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5150 Preamble += "typedef struct objc_object Protocol;\n";
5151 Preamble += "#define _REWRITER_typedef_Protocol\n";
5152 Preamble += "#endif\n";
5153 if (LangOpts.MicrosoftExt) {
5154 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5155 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5156 } else
5157 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5158 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5159 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5160 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5161 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5162 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5163 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5164 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5165 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5166 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5167 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5168 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5169 Preamble += "(const char *);\n";
5170 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5171 Preamble += "(struct objc_class *);\n";
5172 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5173 Preamble += "(const char *);\n";
Fariborz Jahanianb1228182012-03-15 22:42:15 +00005174 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005175 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5176 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5177 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5178 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5179 Preamble += "(struct objc_class *, struct objc_object *);\n";
5180 // @synchronized hooks.
Fariborz Jahanian542125f2012-03-16 21:33:16 +00005181 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(id);\n";
5182 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005183 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5184 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5185 Preamble += "struct __objcFastEnumerationState {\n\t";
5186 Preamble += "unsigned long state;\n\t";
5187 Preamble += "void **itemsPtr;\n\t";
5188 Preamble += "unsigned long *mutationsPtr;\n\t";
5189 Preamble += "unsigned long extra[5];\n};\n";
5190 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5191 Preamble += "#define __FASTENUMERATIONSTATE\n";
5192 Preamble += "#endif\n";
5193 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5194 Preamble += "struct __NSConstantStringImpl {\n";
5195 Preamble += " int *isa;\n";
5196 Preamble += " int flags;\n";
5197 Preamble += " char *str;\n";
5198 Preamble += " long length;\n";
5199 Preamble += "};\n";
5200 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5201 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5202 Preamble += "#else\n";
5203 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5204 Preamble += "#endif\n";
5205 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5206 Preamble += "#endif\n";
5207 // Blocks preamble.
5208 Preamble += "#ifndef BLOCK_IMPL\n";
5209 Preamble += "#define BLOCK_IMPL\n";
5210 Preamble += "struct __block_impl {\n";
5211 Preamble += " void *isa;\n";
5212 Preamble += " int Flags;\n";
5213 Preamble += " int Reserved;\n";
5214 Preamble += " void *FuncPtr;\n";
5215 Preamble += "};\n";
5216 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5217 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5218 Preamble += "extern \"C\" __declspec(dllexport) "
5219 "void _Block_object_assign(void *, const void *, const int);\n";
5220 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5221 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5222 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5223 Preamble += "#else\n";
5224 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5225 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5226 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5227 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5228 Preamble += "#endif\n";
5229 Preamble += "#endif\n";
5230 if (LangOpts.MicrosoftExt) {
5231 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5232 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5233 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5234 Preamble += "#define __attribute__(X)\n";
5235 Preamble += "#endif\n";
5236 Preamble += "#define __weak\n";
5237 }
5238 else {
5239 Preamble += "#define __block\n";
5240 Preamble += "#define __weak\n";
5241 }
5242 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5243 // as this avoids warning in any 64bit/32bit compilation model.
5244 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5245}
5246
5247/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5248/// ivar offset.
5249void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5250 std::string &Result) {
5251 if (ivar->isBitField()) {
5252 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5253 // place all bitfields at offset 0.
5254 Result += "0";
5255 } else {
5256 Result += "__OFFSETOFIVAR__(struct ";
5257 Result += ivar->getContainingInterface()->getNameAsString();
5258 if (LangOpts.MicrosoftExt)
5259 Result += "_IMPL";
5260 Result += ", ";
5261 Result += ivar->getNameAsString();
5262 Result += ")";
5263 }
5264}
5265
5266/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5267/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005268/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005269/// char *attributes;
5270/// }
5271
5272/// struct _prop_list_t {
5273/// uint32_t entsize; // sizeof(struct _prop_t)
5274/// uint32_t count_of_properties;
5275/// struct _prop_t prop_list[count_of_properties];
5276/// }
5277
5278/// struct _protocol_t;
5279
5280/// struct _protocol_list_t {
5281/// long protocol_count; // Note, this is 32/64 bit
5282/// struct _protocol_t * protocol_list[protocol_count];
5283/// }
5284
5285/// struct _objc_method {
5286/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005287/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005288/// char *_imp;
5289/// }
5290
5291/// struct _method_list_t {
5292/// uint32_t entsize; // sizeof(struct _objc_method)
5293/// uint32_t method_count;
5294/// struct _objc_method method_list[method_count];
5295/// }
5296
5297/// struct _protocol_t {
5298/// id isa; // NULL
5299/// const char * const protocol_name;
5300/// const struct _protocol_list_t * protocol_list; // super protocols
5301/// const struct method_list_t * const instance_methods;
5302/// const struct method_list_t * const class_methods;
5303/// const struct method_list_t *optionalInstanceMethods;
5304/// const struct method_list_t *optionalClassMethods;
5305/// const struct _prop_list_t * properties;
5306/// const uint32_t size; // sizeof(struct _protocol_t)
5307/// const uint32_t flags; // = 0
5308/// const char ** extendedMethodTypes;
5309/// }
5310
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005311/// struct _ivar_t {
5312/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005313/// const char *name;
5314/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005315/// uint32_t alignment;
5316/// uint32_t size;
5317/// }
5318
5319/// struct _ivar_list_t {
5320/// uint32 entsize; // sizeof(struct _ivar_t)
5321/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005322/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005323/// }
5324
5325/// struct _class_ro_t {
5326/// uint32_t const flags;
5327/// uint32_t const instanceStart;
5328/// uint32_t const instanceSize;
5329/// uint32_t const reserved; // only when building for 64bit targets
5330/// const uint8_t * const ivarLayout;
5331/// const char *const name;
5332/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005333/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005334/// const struct _ivar_list_t *const ivars;
5335/// const uint8_t * const weakIvarLayout;
5336/// const struct _prop_list_t * const properties;
5337/// }
5338
5339/// struct _class_t {
5340/// struct _class_t *isa;
5341/// struct _class_t * const superclass;
5342/// void *cache;
5343/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005344/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005345/// }
5346
5347/// struct _category_t {
5348/// const char * const name;
5349/// struct _class_t *const cls;
5350/// const struct _method_list_t * const instance_methods;
5351/// const struct _method_list_t * const class_methods;
5352/// const struct _protocol_list_t * const protocols;
5353/// const struct _prop_list_t * const properties;
5354/// }
5355
5356/// MessageRefTy - LLVM for:
5357/// struct _message_ref_t {
5358/// IMP messenger;
5359/// SEL name;
5360/// };
5361
5362/// SuperMessageRefTy - LLVM for:
5363/// struct _super_message_ref_t {
5364/// SUPER_IMP messenger;
5365/// SEL name;
5366/// };
5367
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005368static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005369 static bool meta_data_declared = false;
5370 if (meta_data_declared)
5371 return;
5372
5373 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005374 Result += "\tconst char *name;\n";
5375 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005376 Result += "};\n";
5377
5378 Result += "\nstruct _protocol_t;\n";
5379
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005380 Result += "\nstruct _objc_method {\n";
5381 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005382 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005383 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005384 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005385
5386 Result += "\nstruct _protocol_t {\n";
5387 Result += "\tvoid * isa; // NULL\n";
5388 Result += "\tconst char * const protocol_name;\n";
5389 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5390 Result += "\tconst struct method_list_t * const instance_methods;\n";
5391 Result += "\tconst struct method_list_t * const class_methods;\n";
5392 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5393 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5394 Result += "\tconst struct _prop_list_t * properties;\n";
5395 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5396 Result += "\tconst unsigned int flags; // = 0\n";
5397 Result += "\tconst char ** extendedMethodTypes;\n";
5398 Result += "};\n";
5399
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005400 Result += "\nstruct _ivar_t {\n";
5401 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005402 Result += "\tconst char *name;\n";
5403 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005404 Result += "\tunsigned int alignment;\n";
5405 Result += "\tunsigned int size;\n";
5406 Result += "};\n";
5407
5408 Result += "\nstruct _class_ro_t {\n";
5409 Result += "\tunsigned int const flags;\n";
5410 Result += "\tunsigned int instanceStart;\n";
5411 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005412 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5413 if (Triple.getArch() == llvm::Triple::x86_64)
5414 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005415 Result += "\tconst unsigned char * const ivarLayout;\n";
5416 Result += "\tconst char *const name;\n";
5417 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5418 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5419 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5420 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5421 Result += "\tconst struct _prop_list_t *const properties;\n";
5422 Result += "};\n";
5423
5424 Result += "\nstruct _class_t {\n";
5425 Result += "\tstruct _class_t *isa;\n";
5426 Result += "\tstruct _class_t *const superclass;\n";
5427 Result += "\tvoid *cache;\n";
5428 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005429 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005430 Result += "};\n";
5431
5432 Result += "\nstruct _category_t {\n";
5433 Result += "\tconst char * const name;\n";
5434 Result += "\tstruct _class_t *const cls;\n";
5435 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5436 Result += "\tconst struct _method_list_t *const class_methods;\n";
5437 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5438 Result += "\tconst struct _prop_list_t *const properties;\n";
5439 Result += "};\n";
5440
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005441 Result += "extern void *_objc_empty_cache;\n";
5442 Result += "extern void *_objc_empty_vtable;\n";
5443
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005444 meta_data_declared = true;
5445}
5446
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005447static void Write_protocol_list_t_TypeDecl(std::string &Result,
5448 long super_protocol_count) {
5449 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5450 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5451 Result += "\tstruct _protocol_t *super_protocols[";
5452 Result += utostr(super_protocol_count); Result += "];\n";
5453 Result += "}";
5454}
5455
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005456static void Write_method_list_t_TypeDecl(std::string &Result,
5457 unsigned int method_count) {
5458 Result += "struct /*_method_list_t*/"; Result += " {\n";
5459 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5460 Result += "\tunsigned int method_count;\n";
5461 Result += "\tstruct _objc_method method_list[";
5462 Result += utostr(method_count); Result += "];\n";
5463 Result += "}";
5464}
5465
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005466static void Write__prop_list_t_TypeDecl(std::string &Result,
5467 unsigned int property_count) {
5468 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5469 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5470 Result += "\tunsigned int count_of_properties;\n";
5471 Result += "\tstruct _prop_t prop_list[";
5472 Result += utostr(property_count); Result += "];\n";
5473 Result += "}";
5474}
5475
Fariborz Jahanianae932952012-02-10 20:47:10 +00005476static void Write__ivar_list_t_TypeDecl(std::string &Result,
5477 unsigned int ivar_count) {
5478 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5479 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5480 Result += "\tunsigned int count;\n";
5481 Result += "\tstruct _ivar_t ivar_list[";
5482 Result += utostr(ivar_count); Result += "];\n";
5483 Result += "}";
5484}
5485
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005486static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5487 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5488 StringRef VarName,
5489 StringRef ProtocolName) {
5490 if (SuperProtocols.size() > 0) {
5491 Result += "\nstatic ";
5492 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5493 Result += " "; Result += VarName;
5494 Result += ProtocolName;
5495 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5496 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5497 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5498 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5499 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5500 Result += SuperPD->getNameAsString();
5501 if (i == e-1)
5502 Result += "\n};\n";
5503 else
5504 Result += ",\n";
5505 }
5506 }
5507}
5508
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005509static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5510 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005511 ArrayRef<ObjCMethodDecl *> Methods,
5512 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005513 StringRef TopLevelDeclName,
5514 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005515 if (Methods.size() > 0) {
5516 Result += "\nstatic ";
5517 Write_method_list_t_TypeDecl(Result, Methods.size());
5518 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005519 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005520 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5521 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5522 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5523 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5524 ObjCMethodDecl *MD = Methods[i];
5525 if (i == 0)
5526 Result += "\t{{(struct objc_selector *)\"";
5527 else
5528 Result += "\t{(struct objc_selector *)\"";
5529 Result += (MD)->getSelector().getAsString(); Result += "\"";
5530 Result += ", ";
5531 std::string MethodTypeString;
5532 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5533 Result += "\""; Result += MethodTypeString; Result += "\"";
5534 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005535 if (!MethodImpl)
5536 Result += "0";
5537 else {
5538 Result += "(void *)";
5539 Result += RewriteObj.MethodInternalNames[MD];
5540 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005541 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005542 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005543 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005544 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005545 }
5546 Result += "};\n";
5547 }
5548}
5549
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005550static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005551 ASTContext *Context, std::string &Result,
5552 ArrayRef<ObjCPropertyDecl *> Properties,
5553 const Decl *Container,
5554 StringRef VarName,
5555 StringRef ProtocolName) {
5556 if (Properties.size() > 0) {
5557 Result += "\nstatic ";
5558 Write__prop_list_t_TypeDecl(Result, Properties.size());
5559 Result += " "; Result += VarName;
5560 Result += ProtocolName;
5561 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5562 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5563 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5564 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5565 ObjCPropertyDecl *PropDecl = Properties[i];
5566 if (i == 0)
5567 Result += "\t{{\"";
5568 else
5569 Result += "\t{\"";
5570 Result += PropDecl->getName(); Result += "\",";
5571 std::string PropertyTypeString, QuotePropertyTypeString;
5572 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5573 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5574 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5575 if (i == e-1)
5576 Result += "}}\n";
5577 else
5578 Result += "},\n";
5579 }
5580 Result += "};\n";
5581 }
5582}
5583
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005584// Metadata flags
5585enum MetaDataDlags {
5586 CLS = 0x0,
5587 CLS_META = 0x1,
5588 CLS_ROOT = 0x2,
5589 OBJC2_CLS_HIDDEN = 0x10,
5590 CLS_EXCEPTION = 0x20,
5591
5592 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5593 CLS_HAS_IVAR_RELEASER = 0x40,
5594 /// class was compiled with -fobjc-arr
5595 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5596};
5597
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005598static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5599 unsigned int flags,
5600 const std::string &InstanceStart,
5601 const std::string &InstanceSize,
5602 ArrayRef<ObjCMethodDecl *>baseMethods,
5603 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5604 ArrayRef<ObjCIvarDecl *>ivars,
5605 ArrayRef<ObjCPropertyDecl *>Properties,
5606 StringRef VarName,
5607 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005608 Result += "\nstatic struct _class_ro_t ";
5609 Result += VarName; Result += ClassName;
5610 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5611 Result += "\t";
5612 Result += llvm::utostr(flags); Result += ", ";
5613 Result += InstanceStart; Result += ", ";
5614 Result += InstanceSize; Result += ", \n";
5615 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005616 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5617 if (Triple.getArch() == llvm::Triple::x86_64)
5618 // uint32_t const reserved; // only when building for 64bit targets
5619 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005620 // const uint8_t * const ivarLayout;
5621 Result += "0, \n\t";
5622 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005623 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005624 if (baseMethods.size() > 0) {
5625 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005626 if (metaclass)
5627 Result += "_OBJC_$_CLASS_METHODS_";
5628 else
5629 Result += "_OBJC_$_INSTANCE_METHODS_";
5630 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005631 Result += ",\n\t";
5632 }
5633 else
5634 Result += "0, \n\t";
5635
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005636 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005637 Result += "(const struct _objc_protocol_list *)&";
5638 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5639 Result += ",\n\t";
5640 }
5641 else
5642 Result += "0, \n\t";
5643
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005644 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005645 Result += "(const struct _ivar_list_t *)&";
5646 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5647 Result += ",\n\t";
5648 }
5649 else
5650 Result += "0, \n\t";
5651
5652 // weakIvarLayout
5653 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005654 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005655 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005656 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005657 Result += ",\n";
5658 }
5659 else
5660 Result += "0, \n";
5661
5662 Result += "};\n";
5663}
5664
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005665static void Write_class_t(ASTContext *Context, std::string &Result,
5666 StringRef VarName,
5667 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005668
5669 if (metadata && !CDecl->getSuperClass()) {
5670 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005671 Result += "\n";
5672 if (CDecl->getImplementation())
5673 Result += "__declspec(dllexport) ";
5674 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005675 Result += CDecl->getNameAsString();
5676 Result += ";\n";
5677 }
5678 // Also, for possibility of 'super' metadata class not having been defined yet.
5679 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005680 Result += "\n";
5681 if (CDecl->getSuperClass()->getImplementation())
5682 Result += "__declspec(dllexport) ";
5683 Result += "extern struct _class_t ";
5684 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005685 Result += CDecl->getSuperClass()->getNameAsString();
5686 Result += ";\n";
5687 }
5688
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005689 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005690 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5691 Result += "\t";
5692 if (metadata) {
5693 if (CDecl->getSuperClass()) {
5694 Result += "&"; Result += VarName;
5695 Result += CDecl->getSuperClass()->getNameAsString();
5696 Result += ",\n\t";
5697 Result += "&"; Result += VarName;
5698 Result += CDecl->getSuperClass()->getNameAsString();
5699 Result += ",\n\t";
5700 }
5701 else {
5702 Result += "&"; Result += VarName;
5703 Result += CDecl->getNameAsString();
5704 Result += ",\n\t";
5705 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5706 Result += ",\n\t";
5707 }
5708 }
5709 else {
5710 Result += "&OBJC_METACLASS_$_";
5711 Result += CDecl->getNameAsString();
5712 Result += ",\n\t";
5713 if (CDecl->getSuperClass()) {
5714 Result += "&"; Result += VarName;
5715 Result += CDecl->getSuperClass()->getNameAsString();
5716 Result += ",\n\t";
5717 }
5718 else
5719 Result += "0,\n\t";
5720 }
5721 Result += "(void *)&_objc_empty_cache,\n\t";
5722 Result += "(void *)&_objc_empty_vtable,\n\t";
5723 if (metadata)
5724 Result += "&_OBJC_METACLASS_RO_$_";
5725 else
5726 Result += "&_OBJC_CLASS_RO_$_";
5727 Result += CDecl->getNameAsString();
5728 Result += ",\n};\n";
5729}
5730
Fariborz Jahanian61186122012-02-17 18:40:41 +00005731static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5732 std::string &Result,
5733 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005734 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005735 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5736 ArrayRef<ObjCMethodDecl *> ClassMethods,
5737 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5738 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005739
5740 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005741 // must declare an extern class object in case this class is not implemented
5742 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005743 Result += "\n";
5744 if (ClassDecl->getImplementation())
5745 Result += "__declspec(dllexport) ";
5746
5747 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005748 Result += "OBJC_CLASS_$_"; Result += ClassName;
5749 Result += ";\n";
5750
Fariborz Jahanian61186122012-02-17 18:40:41 +00005751 Result += "\nstatic struct _category_t ";
5752 Result += "_OBJC_$_CATEGORY_";
5753 Result += ClassName; Result += "_$_"; Result += CatName;
5754 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5755 Result += "{\n";
5756 Result += "\t\""; Result += ClassName; Result += "\",\n";
5757 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5758 Result += ",\n";
5759 if (InstanceMethods.size() > 0) {
5760 Result += "\t(const struct _method_list_t *)&";
5761 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5762 Result += ClassName; Result += "_$_"; Result += CatName;
5763 Result += ",\n";
5764 }
5765 else
5766 Result += "\t0,\n";
5767
5768 if (ClassMethods.size() > 0) {
5769 Result += "\t(const struct _method_list_t *)&";
5770 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5771 Result += ClassName; Result += "_$_"; Result += CatName;
5772 Result += ",\n";
5773 }
5774 else
5775 Result += "\t0,\n";
5776
5777 if (RefedProtocols.size() > 0) {
5778 Result += "\t(const struct _protocol_list_t *)&";
5779 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5780 Result += ClassName; Result += "_$_"; Result += CatName;
5781 Result += ",\n";
5782 }
5783 else
5784 Result += "\t0,\n";
5785
5786 if (ClassProperties.size() > 0) {
5787 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5788 Result += ClassName; Result += "_$_"; Result += CatName;
5789 Result += ",\n";
5790 }
5791 else
5792 Result += "\t0,\n";
5793
5794 Result += "};\n";
5795}
5796
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005797static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5798 ASTContext *Context, std::string &Result,
5799 ArrayRef<ObjCMethodDecl *> Methods,
5800 StringRef VarName,
5801 StringRef ProtocolName) {
5802 if (Methods.size() == 0)
5803 return;
5804
5805 Result += "\nstatic const char *";
5806 Result += VarName; Result += ProtocolName;
5807 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5808 Result += "{\n";
5809 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5810 ObjCMethodDecl *MD = Methods[i];
5811 std::string MethodTypeString, QuoteMethodTypeString;
5812 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5813 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5814 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5815 if (i == e-1)
5816 Result += "\n};\n";
5817 else {
5818 Result += ",\n";
5819 }
5820 }
5821}
5822
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005823static void Write_IvarOffsetVar(ASTContext *Context,
5824 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005825 ArrayRef<ObjCIvarDecl *> Ivars,
5826 StringRef VarName,
5827 StringRef ClassName) {
5828 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5829 // this is what happens:
5830 /**
5831 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5832 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5833 Class->getVisibility() == HiddenVisibility)
5834 Visibility shoud be: HiddenVisibility;
5835 else
5836 Visibility shoud be: DefaultVisibility;
5837 */
5838
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005839 Result += "\n";
5840 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5841 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005842 if (Context->getLangOpts().MicrosoftExt)
5843 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5844
5845 if (!Context->getLangOpts().MicrosoftExt ||
5846 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005847 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005848 Result += "unsigned long int ";
5849 else
5850 Result += "__declspec(dllexport) unsigned long int ";
5851
5852 Result += VarName;
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005853 Result += ClassName; Result += "_";
5854 Result += IvarDecl->getName();
5855 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5856 Result += " = ";
5857 if (IvarDecl->isBitField()) {
5858 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5859 // place all bitfields at offset 0.
5860 Result += "0;\n";
5861 }
5862 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005863 Result += "__OFFSETOFIVAR__(struct ";
5864 Result += ClassName;
5865 Result += "_IMPL, ";
5866 Result += IvarDecl->getName(); Result += ");\n";
5867 }
5868 }
5869}
5870
Fariborz Jahanianae932952012-02-10 20:47:10 +00005871static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5872 ASTContext *Context, std::string &Result,
5873 ArrayRef<ObjCIvarDecl *> Ivars,
5874 StringRef VarName,
5875 StringRef ClassName) {
5876 if (Ivars.size() > 0) {
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005877 Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005878
Fariborz Jahanianae932952012-02-10 20:47:10 +00005879 Result += "\nstatic ";
5880 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5881 Result += " "; Result += VarName;
5882 Result += ClassName;
5883 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5884 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5885 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5886 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5887 ObjCIvarDecl *IvarDecl = Ivars[i];
5888 if (i == 0)
5889 Result += "\t{{";
5890 else
5891 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005892
5893 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5894 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5895 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005896
5897 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5898 std::string IvarTypeString, QuoteIvarTypeString;
5899 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5900 IvarDecl);
5901 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5902 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5903
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005904 // FIXME. this alignment represents the host alignment and need be changed to
5905 // represent the target alignment.
5906 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5907 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005908 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005909 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5910 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005911 if (i == e-1)
5912 Result += "}}\n";
5913 else
5914 Result += "},\n";
5915 }
5916 Result += "};\n";
5917 }
5918}
5919
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005920/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005921void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5922 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005923
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005924 // Do not synthesize the protocol more than once.
5925 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5926 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005927 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005928
5929 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5930 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005931 // Must write out all protocol definitions in current qualifier list,
5932 // and in their nested qualifiers before writing out current definition.
5933 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5934 E = PDecl->protocol_end(); I != E; ++I)
5935 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005936
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005937 // Construct method lists.
5938 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5939 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5940 for (ObjCProtocolDecl::instmeth_iterator
5941 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5942 I != E; ++I) {
5943 ObjCMethodDecl *MD = *I;
5944 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5945 OptInstanceMethods.push_back(MD);
5946 } else {
5947 InstanceMethods.push_back(MD);
5948 }
5949 }
5950
5951 for (ObjCProtocolDecl::classmeth_iterator
5952 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5953 I != E; ++I) {
5954 ObjCMethodDecl *MD = *I;
5955 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5956 OptClassMethods.push_back(MD);
5957 } else {
5958 ClassMethods.push_back(MD);
5959 }
5960 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005961 std::vector<ObjCMethodDecl *> AllMethods;
5962 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5963 AllMethods.push_back(InstanceMethods[i]);
5964 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5965 AllMethods.push_back(ClassMethods[i]);
5966 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5967 AllMethods.push_back(OptInstanceMethods[i]);
5968 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5969 AllMethods.push_back(OptClassMethods[i]);
5970
5971 Write__extendedMethodTypes_initializer(*this, Context, Result,
5972 AllMethods,
5973 "_OBJC_PROTOCOL_METHOD_TYPES_",
5974 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005975 // Protocol's super protocol list
5976 std::vector<ObjCProtocolDecl *> SuperProtocols;
5977 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5978 E = PDecl->protocol_end(); I != E; ++I)
5979 SuperProtocols.push_back(*I);
5980
5981 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5982 "_OBJC_PROTOCOL_REFS_",
5983 PDecl->getNameAsString());
5984
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005985 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005986 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005987 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005988
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005989 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005990 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005991 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005992
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005993 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005994 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005995 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005996
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005997 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005998 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005999 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006000
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006001 // Protocol's property metadata.
6002 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6003 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6004 E = PDecl->prop_end(); I != E; ++I)
6005 ProtocolProperties.push_back(*I);
6006
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006007 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006008 /* Container */0,
6009 "_OBJC_PROTOCOL_PROPERTIES_",
6010 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006011
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006012 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006013 Result += "\n";
6014 if (LangOpts.MicrosoftExt)
6015 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006016 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006017 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006018 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6019 Result += "\t0,\n"; // id is; is null
6020 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006021 if (SuperProtocols.size() > 0) {
6022 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6023 Result += PDecl->getNameAsString(); Result += ",\n";
6024 }
6025 else
6026 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006027 if (InstanceMethods.size() > 0) {
6028 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6029 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006030 }
6031 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006032 Result += "\t0,\n";
6033
6034 if (ClassMethods.size() > 0) {
6035 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6036 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006037 }
6038 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006039 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006040
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006041 if (OptInstanceMethods.size() > 0) {
6042 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6043 Result += PDecl->getNameAsString(); Result += ",\n";
6044 }
6045 else
6046 Result += "\t0,\n";
6047
6048 if (OptClassMethods.size() > 0) {
6049 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6050 Result += PDecl->getNameAsString(); Result += ",\n";
6051 }
6052 else
6053 Result += "\t0,\n";
6054
6055 if (ProtocolProperties.size() > 0) {
6056 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6057 Result += PDecl->getNameAsString(); Result += ",\n";
6058 }
6059 else
6060 Result += "\t0,\n";
6061
6062 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6063 Result += "\t0,\n";
6064
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006065 if (AllMethods.size() > 0) {
6066 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6067 Result += PDecl->getNameAsString();
6068 Result += "\n};\n";
6069 }
6070 else
6071 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006072
6073 // Use this protocol meta-data to build protocol list table in section
6074 // .objc_protolist$B
6075 // Unspecified visibility means 'private extern'.
6076 if (LangOpts.MicrosoftExt)
6077 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6078 Result += "struct _protocol_t *";
6079 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6080 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6081 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006082
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006083 // Mark this protocol as having been generated.
6084 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6085 llvm_unreachable("protocol already synthesized");
6086
6087}
6088
6089void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6090 const ObjCList<ObjCProtocolDecl> &Protocols,
6091 StringRef prefix, StringRef ClassName,
6092 std::string &Result) {
6093 if (Protocols.empty()) return;
6094
6095 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006096 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006097
6098 // Output the top lovel protocol meta-data for the class.
6099 /* struct _objc_protocol_list {
6100 struct _objc_protocol_list *next;
6101 int protocol_count;
6102 struct _objc_protocol *class_protocols[];
6103 }
6104 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006105 Result += "\n";
6106 if (LangOpts.MicrosoftExt)
6107 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6108 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006109 Result += "\tstruct _objc_protocol_list *next;\n";
6110 Result += "\tint protocol_count;\n";
6111 Result += "\tstruct _objc_protocol *class_protocols[";
6112 Result += utostr(Protocols.size());
6113 Result += "];\n} _OBJC_";
6114 Result += prefix;
6115 Result += "_PROTOCOLS_";
6116 Result += ClassName;
6117 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6118 "{\n\t0, ";
6119 Result += utostr(Protocols.size());
6120 Result += "\n";
6121
6122 Result += "\t,{&_OBJC_PROTOCOL_";
6123 Result += Protocols[0]->getNameAsString();
6124 Result += " \n";
6125
6126 for (unsigned i = 1; i != Protocols.size(); i++) {
6127 Result += "\t ,&_OBJC_PROTOCOL_";
6128 Result += Protocols[i]->getNameAsString();
6129 Result += "\n";
6130 }
6131 Result += "\t }\n};\n";
6132}
6133
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006134/// hasObjCExceptionAttribute - Return true if this class or any super
6135/// class has the __objc_exception__ attribute.
6136/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6137static bool hasObjCExceptionAttribute(ASTContext &Context,
6138 const ObjCInterfaceDecl *OID) {
6139 if (OID->hasAttr<ObjCExceptionAttr>())
6140 return true;
6141 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6142 return hasObjCExceptionAttribute(Context, Super);
6143 return false;
6144}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006146void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6147 std::string &Result) {
6148 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6149
6150 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006151 if (CDecl->isImplicitInterfaceDecl())
6152 assert(false &&
6153 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006154
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006155 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006156 SmallVector<ObjCIvarDecl *, 8> IVars;
6157
6158 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6159 IVD; IVD = IVD->getNextIvar()) {
6160 // Ignore unnamed bit-fields.
6161 if (!IVD->getDeclName())
6162 continue;
6163 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006164 }
6165
Fariborz Jahanianae932952012-02-10 20:47:10 +00006166 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006167 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006168 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006169
6170 // Build _objc_method_list for class's instance methods if needed
6171 SmallVector<ObjCMethodDecl *, 32>
6172 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6173
6174 // If any of our property implementations have associated getters or
6175 // setters, produce metadata for them as well.
6176 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6177 PropEnd = IDecl->propimpl_end();
6178 Prop != PropEnd; ++Prop) {
6179 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6180 continue;
6181 if (!(*Prop)->getPropertyIvarDecl())
6182 continue;
6183 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6184 if (!PD)
6185 continue;
6186 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6187 if (!Getter->isDefined())
6188 InstanceMethods.push_back(Getter);
6189 if (PD->isReadOnly())
6190 continue;
6191 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6192 if (!Setter->isDefined())
6193 InstanceMethods.push_back(Setter);
6194 }
6195
6196 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6197 "_OBJC_$_INSTANCE_METHODS_",
6198 IDecl->getNameAsString(), true);
6199
6200 SmallVector<ObjCMethodDecl *, 32>
6201 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6202
6203 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6204 "_OBJC_$_CLASS_METHODS_",
6205 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006206
6207 // Protocols referenced in class declaration?
6208 // Protocol's super protocol list
6209 std::vector<ObjCProtocolDecl *> RefedProtocols;
6210 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6211 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6212 E = Protocols.end();
6213 I != E; ++I) {
6214 RefedProtocols.push_back(*I);
6215 // Must write out all protocol definitions in current qualifier list,
6216 // and in their nested qualifiers before writing out current definition.
6217 RewriteObjCProtocolMetaData(*I, Result);
6218 }
6219
6220 Write_protocol_list_initializer(Context, Result,
6221 RefedProtocols,
6222 "_OBJC_CLASS_PROTOCOLS_$_",
6223 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006224
6225 // Protocol's property metadata.
6226 std::vector<ObjCPropertyDecl *> ClassProperties;
6227 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6228 E = CDecl->prop_end(); I != E; ++I)
6229 ClassProperties.push_back(*I);
6230
6231 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6232 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006233 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006234 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006235
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006236
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006237 // Data for initializing _class_ro_t metaclass meta-data
6238 uint32_t flags = CLS_META;
6239 std::string InstanceSize;
6240 std::string InstanceStart;
6241
6242
6243 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6244 if (classIsHidden)
6245 flags |= OBJC2_CLS_HIDDEN;
6246
6247 if (!CDecl->getSuperClass())
6248 // class is root
6249 flags |= CLS_ROOT;
6250 InstanceSize = "sizeof(struct _class_t)";
6251 InstanceStart = InstanceSize;
6252 Write__class_ro_t_initializer(Context, Result, flags,
6253 InstanceStart, InstanceSize,
6254 ClassMethods,
6255 0,
6256 0,
6257 0,
6258 "_OBJC_METACLASS_RO_$_",
6259 CDecl->getNameAsString());
6260
6261
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006262 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006263 flags = CLS;
6264 if (classIsHidden)
6265 flags |= OBJC2_CLS_HIDDEN;
6266
6267 if (hasObjCExceptionAttribute(*Context, CDecl))
6268 flags |= CLS_EXCEPTION;
6269
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006270 if (!CDecl->getSuperClass())
6271 // class is root
6272 flags |= CLS_ROOT;
6273
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006274 InstanceSize.clear();
6275 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006276 if (!ObjCSynthesizedStructs.count(CDecl)) {
6277 InstanceSize = "0";
6278 InstanceStart = "0";
6279 }
6280 else {
6281 InstanceSize = "sizeof(struct ";
6282 InstanceSize += CDecl->getNameAsString();
6283 InstanceSize += "_IMPL)";
6284
6285 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6286 if (IVD) {
6287 InstanceStart += "__OFFSETOFIVAR__(struct ";
6288 InstanceStart += CDecl->getNameAsString();
6289 InstanceStart += "_IMPL, ";
6290 InstanceStart += IVD->getNameAsString();
6291 InstanceStart += ")";
6292 }
6293 else
6294 InstanceStart = InstanceSize;
6295 }
6296 Write__class_ro_t_initializer(Context, Result, flags,
6297 InstanceStart, InstanceSize,
6298 InstanceMethods,
6299 RefedProtocols,
6300 IVars,
6301 ClassProperties,
6302 "_OBJC_CLASS_RO_$_",
6303 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006304
6305 Write_class_t(Context, Result,
6306 "OBJC_METACLASS_$_",
6307 CDecl, /*metaclass*/true);
6308
6309 Write_class_t(Context, Result,
6310 "OBJC_CLASS_$_",
6311 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006312
6313 if (ImplementationIsNonLazy(IDecl))
6314 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006315
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006316}
6317
6318void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6319 int ClsDefCount = ClassImplementation.size();
6320 int CatDefCount = CategoryImplementation.size();
6321
6322 // For each implemented class, write out all its meta data.
6323 for (int i = 0; i < ClsDefCount; i++)
6324 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6325
6326 // For each implemented category, write out all its meta data.
6327 for (int i = 0; i < CatDefCount; i++)
6328 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6329
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006330 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006331 if (LangOpts.MicrosoftExt)
6332 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006333 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6334 Result += llvm::utostr(ClsDefCount); Result += "]";
6335 Result +=
6336 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6337 "regular,no_dead_strip\")))= {\n";
6338 for (int i = 0; i < ClsDefCount; i++) {
6339 Result += "\t&OBJC_CLASS_$_";
6340 Result += ClassImplementation[i]->getNameAsString();
6341 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006342 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006343 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006344
6345 if (!DefinedNonLazyClasses.empty()) {
6346 if (LangOpts.MicrosoftExt)
6347 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6348 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6349 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6350 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6351 Result += ",\n";
6352 }
6353 Result += "};\n";
6354 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006355 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006356
6357 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006358 if (LangOpts.MicrosoftExt)
6359 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006360 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6361 Result += llvm::utostr(CatDefCount); Result += "]";
6362 Result +=
6363 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6364 "regular,no_dead_strip\")))= {\n";
6365 for (int i = 0; i < CatDefCount; i++) {
6366 Result += "\t&_OBJC_$_CATEGORY_";
6367 Result +=
6368 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6369 Result += "_$_";
6370 Result += CategoryImplementation[i]->getNameAsString();
6371 Result += ",\n";
6372 }
6373 Result += "};\n";
6374 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006375
6376 if (!DefinedNonLazyCategories.empty()) {
6377 if (LangOpts.MicrosoftExt)
6378 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6379 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6380 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6381 Result += "\t&_OBJC_$_CATEGORY_";
6382 Result +=
6383 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6384 Result += "_$_";
6385 Result += DefinedNonLazyCategories[i]->getNameAsString();
6386 Result += ",\n";
6387 }
6388 Result += "};\n";
6389 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006390}
6391
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006392void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6393 if (LangOpts.MicrosoftExt)
6394 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6395
6396 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6397 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006398 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006399}
6400
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006401/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6402/// implementation.
6403void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6404 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006405 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006406 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6407 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006408 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006409 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6410 CDecl = CDecl->getNextClassCategory())
6411 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6412 break;
6413
6414 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006415 FullCategoryName += "_$_";
6416 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006417
6418 // Build _objc_method_list for class's instance methods if needed
6419 SmallVector<ObjCMethodDecl *, 32>
6420 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6421
6422 // If any of our property implementations have associated getters or
6423 // setters, produce metadata for them as well.
6424 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6425 PropEnd = IDecl->propimpl_end();
6426 Prop != PropEnd; ++Prop) {
6427 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6428 continue;
6429 if (!(*Prop)->getPropertyIvarDecl())
6430 continue;
6431 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6432 if (!PD)
6433 continue;
6434 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6435 InstanceMethods.push_back(Getter);
6436 if (PD->isReadOnly())
6437 continue;
6438 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6439 InstanceMethods.push_back(Setter);
6440 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006441
Fariborz Jahanian61186122012-02-17 18:40:41 +00006442 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6443 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6444 FullCategoryName, true);
6445
6446 SmallVector<ObjCMethodDecl *, 32>
6447 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6448
6449 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6450 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6451 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006452
6453 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006454 // Protocol's super protocol list
6455 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006456 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6457 E = CDecl->protocol_end();
6458
6459 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006460 RefedProtocols.push_back(*I);
6461 // Must write out all protocol definitions in current qualifier list,
6462 // and in their nested qualifiers before writing out current definition.
6463 RewriteObjCProtocolMetaData(*I, Result);
6464 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006465
Fariborz Jahanian61186122012-02-17 18:40:41 +00006466 Write_protocol_list_initializer(Context, Result,
6467 RefedProtocols,
6468 "_OBJC_CATEGORY_PROTOCOLS_$_",
6469 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006470
Fariborz Jahanian61186122012-02-17 18:40:41 +00006471 // Protocol's property metadata.
6472 std::vector<ObjCPropertyDecl *> ClassProperties;
6473 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6474 E = CDecl->prop_end(); I != E; ++I)
6475 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006476
Fariborz Jahanian61186122012-02-17 18:40:41 +00006477 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6478 /* Container */0,
6479 "_OBJC_$_PROP_LIST_",
6480 FullCategoryName);
6481
6482 Write_category_t(*this, Context, Result,
6483 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006484 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006485 InstanceMethods,
6486 ClassMethods,
6487 RefedProtocols,
6488 ClassProperties);
6489
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006490 // Determine if this category is also "non-lazy".
6491 if (ImplementationIsNonLazy(IDecl))
6492 DefinedNonLazyCategories.push_back(CDecl);
6493
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006494}
6495
6496// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6497/// class methods.
6498template<typename MethodIterator>
6499void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6500 MethodIterator MethodEnd,
6501 bool IsInstanceMethod,
6502 StringRef prefix,
6503 StringRef ClassName,
6504 std::string &Result) {
6505 if (MethodBegin == MethodEnd) return;
6506
6507 if (!objc_impl_method) {
6508 /* struct _objc_method {
6509 SEL _cmd;
6510 char *method_types;
6511 void *_imp;
6512 }
6513 */
6514 Result += "\nstruct _objc_method {\n";
6515 Result += "\tSEL _cmd;\n";
6516 Result += "\tchar *method_types;\n";
6517 Result += "\tvoid *_imp;\n";
6518 Result += "};\n";
6519
6520 objc_impl_method = true;
6521 }
6522
6523 // Build _objc_method_list for class's methods if needed
6524
6525 /* struct {
6526 struct _objc_method_list *next_method;
6527 int method_count;
6528 struct _objc_method method_list[];
6529 }
6530 */
6531 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006532 Result += "\n";
6533 if (LangOpts.MicrosoftExt) {
6534 if (IsInstanceMethod)
6535 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6536 else
6537 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6538 }
6539 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006540 Result += "\tstruct _objc_method_list *next_method;\n";
6541 Result += "\tint method_count;\n";
6542 Result += "\tstruct _objc_method method_list[";
6543 Result += utostr(NumMethods);
6544 Result += "];\n} _OBJC_";
6545 Result += prefix;
6546 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6547 Result += "_METHODS_";
6548 Result += ClassName;
6549 Result += " __attribute__ ((used, section (\"__OBJC, __";
6550 Result += IsInstanceMethod ? "inst" : "cls";
6551 Result += "_meth\")))= ";
6552 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6553
6554 Result += "\t,{{(SEL)\"";
6555 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6556 std::string MethodTypeString;
6557 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6558 Result += "\", \"";
6559 Result += MethodTypeString;
6560 Result += "\", (void *)";
6561 Result += MethodInternalNames[*MethodBegin];
6562 Result += "}\n";
6563 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6564 Result += "\t ,{(SEL)\"";
6565 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6566 std::string MethodTypeString;
6567 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6568 Result += "\", \"";
6569 Result += MethodTypeString;
6570 Result += "\", (void *)";
6571 Result += MethodInternalNames[*MethodBegin];
6572 Result += "}\n";
6573 }
6574 Result += "\t }\n};\n";
6575}
6576
6577Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6578 SourceRange OldRange = IV->getSourceRange();
6579 Expr *BaseExpr = IV->getBase();
6580
6581 // Rewrite the base, but without actually doing replaces.
6582 {
6583 DisableReplaceStmtScope S(*this);
6584 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6585 IV->setBase(BaseExpr);
6586 }
6587
6588 ObjCIvarDecl *D = IV->getDecl();
6589
6590 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006591
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006592 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6593 const ObjCInterfaceType *iFaceDecl =
6594 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6595 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6596 // lookup which class implements the instance variable.
6597 ObjCInterfaceDecl *clsDeclared = 0;
6598 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6599 clsDeclared);
6600 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6601
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006602 // Build name of symbol holding ivar offset.
6603 std::string IvarOffsetName = "OBJC_IVAR_$_";
6604 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6605 IvarOffsetName += "_";
6606 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006607 ReferencedIvars[clsDeclared].insert(D);
6608
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006609 // cast offset to "char *".
6610 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6611 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006612 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006613 BaseExpr);
6614 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6615 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6616 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006617 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6618 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006619 SourceLocation());
6620 BinaryOperator *addExpr =
6621 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6622 Context->getPointerType(Context->CharTy),
6623 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006624 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006625 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6626 SourceLocation(),
6627 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006628 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006629 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006630 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006631
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006632 castExpr = NoTypeInfoCStyleCastExpr(Context,
6633 castT,
6634 CK_BitCast,
6635 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006636 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006637 VK_LValue, OK_Ordinary,
6638 SourceLocation());
6639 PE = new (Context) ParenExpr(OldRange.getBegin(),
6640 OldRange.getEnd(),
6641 Exp);
6642
6643 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006644 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006645
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006646 ReplaceStmtWithRange(IV, Replacement, OldRange);
6647 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006648}
6649