blob: 78e0dbce7c17395dffd18d129ff8cb3d6bbb9b54 [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 Jahanian22e2f852012-03-17 17:46:02 +00001706 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001708 const char *lparenBuf = startBuf;
1709 while (*lparenBuf != '(') lparenBuf++;
1710 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001711
1712 buf = "; objc_sync_enter(_sync_obj);\n";
1713 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1714 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1715 buf += "\n\tid sync_exit;";
1716 buf += "\n\t} _sync_exit(_sync_obj);\n";
1717
1718 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1719 // the sync expression is typically a message expression that's already
1720 // been rewritten! (which implies the SourceLocation's are invalid).
1721 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1722 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1723 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1724 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1725
1726 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1727 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1728 assert (*LBraceLocBuf == '{');
1729 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001730
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001731 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001732 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1733 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001734
1735 buf = "} catch (id e) {_rethrow = e;}\n";
1736 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001737 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001738 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001739
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001740 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001741
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001742 return 0;
1743}
1744
1745void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1746{
1747 // Perform a bottom up traversal of all children.
1748 for (Stmt::child_range CI = S->children(); CI; ++CI)
1749 if (*CI)
1750 WarnAboutReturnGotoStmts(*CI);
1751
1752 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1753 Diags.Report(Context->getFullLoc(S->getLocStart()),
1754 TryFinallyContainsReturnDiag);
1755 }
1756 return;
1757}
1758
1759void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1760{
1761 // Perform a bottom up traversal of all children.
1762 for (Stmt::child_range CI = S->children(); CI; ++CI)
1763 if (*CI)
1764 HasReturnStmts(*CI, hasReturns);
1765
1766 if (isa<ReturnStmt>(S))
1767 hasReturns = true;
1768 return;
1769}
1770
1771void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1772 // Perform a bottom up traversal of all children.
1773 for (Stmt::child_range CI = S->children(); CI; ++CI)
1774 if (*CI) {
1775 RewriteTryReturnStmts(*CI);
1776 }
1777 if (isa<ReturnStmt>(S)) {
1778 SourceLocation startLoc = S->getLocStart();
1779 const char *startBuf = SM->getCharacterData(startLoc);
1780
1781 const char *semiBuf = strchr(startBuf, ';');
1782 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1783 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1784
1785 std::string buf;
1786 buf = "{ objc_exception_try_exit(&_stack); return";
1787
1788 ReplaceText(startLoc, 6, buf);
1789 InsertText(onePastSemiLoc, "}");
1790 }
1791 return;
1792}
1793
1794void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1795 // Perform a bottom up traversal of all children.
1796 for (Stmt::child_range CI = S->children(); CI; ++CI)
1797 if (*CI) {
1798 RewriteSyncReturnStmts(*CI, syncExitBuf);
1799 }
1800 if (isa<ReturnStmt>(S)) {
1801 SourceLocation startLoc = S->getLocStart();
1802 const char *startBuf = SM->getCharacterData(startLoc);
1803
1804 const char *semiBuf = strchr(startBuf, ';');
1805 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1806 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1807
1808 std::string buf;
1809 buf = "{ objc_exception_try_exit(&_stack);";
1810 buf += syncExitBuf;
1811 buf += " return";
1812
1813 ReplaceText(startLoc, 6, buf);
1814 InsertText(onePastSemiLoc, "}");
1815 }
1816 return;
1817}
1818
1819Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001820 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001821 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001822 std::string buf;
1823
1824 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001825 if (noCatch)
1826 buf = "{ id volatile _rethrow = 0;\n";
1827 else {
1828 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1829 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001830 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001831 // Get the start location and compute the semi location.
1832 SourceLocation startLoc = S->getLocStart();
1833 const char *startBuf = SM->getCharacterData(startLoc);
1834
1835 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001836 if (finalStmt)
1837 ReplaceText(startLoc, 1, buf);
1838 else
1839 // @try -> try
1840 ReplaceText(startLoc, 1, "");
1841
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001842 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1843 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001844 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001846 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001847 bool AtRemoved = false;
1848 if (catchDecl) {
1849 QualType t = catchDecl->getType();
1850 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1851 // Should be a pointer to a class.
1852 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1853 if (IDecl) {
1854 std::string Result;
1855 startBuf = SM->getCharacterData(startLoc);
1856 assert((*startBuf == '@') && "bogus @catch location");
1857 SourceLocation rParenLoc = Catch->getRParenLoc();
1858 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1859
1860 // _objc_exc_Foo *_e as argument to catch.
1861 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1862 Result += " *_"; Result += catchDecl->getNameAsString();
1863 Result += ")";
1864 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1865 // Foo *e = (Foo *)_e;
1866 Result.clear();
1867 Result = "{ ";
1868 Result += IDecl->getNameAsString();
1869 Result += " *"; Result += catchDecl->getNameAsString();
1870 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1871 Result += "_"; Result += catchDecl->getNameAsString();
1872
1873 Result += "; ";
1874 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1875 ReplaceText(lBraceLoc, 1, Result);
1876 AtRemoved = true;
1877 }
1878 }
1879 }
1880 if (!AtRemoved)
1881 // @catch -> catch
1882 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001883
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001884 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001885 if (finalStmt) {
1886 buf.clear();
1887 if (noCatch)
1888 buf = "catch (id e) {_rethrow = e;}\n";
1889 else
1890 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1891
1892 SourceLocation startFinalLoc = finalStmt->getLocStart();
1893 ReplaceText(startFinalLoc, 8, buf);
1894 Stmt *body = finalStmt->getFinallyBody();
1895 SourceLocation startFinalBodyLoc = body->getLocStart();
1896 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001897 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001898 ReplaceText(startFinalBodyLoc, 1, buf);
1899
1900 SourceLocation endFinalBodyLoc = body->getLocEnd();
1901 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001902 // Now check for any return/continue/go statements within the @try.
1903 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001904 }
1905
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001906 return 0;
1907}
1908
1909// This can't be done with ReplaceStmt(S, ThrowExpr), since
1910// the throw expression is typically a message expression that's already
1911// been rewritten! (which implies the SourceLocation's are invalid).
1912Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1913 // Get the start location and compute the semi location.
1914 SourceLocation startLoc = S->getLocStart();
1915 const char *startBuf = SM->getCharacterData(startLoc);
1916
1917 assert((*startBuf == '@') && "bogus @throw location");
1918
1919 std::string buf;
1920 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1921 if (S->getThrowExpr())
1922 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001923 else
1924 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001925
1926 // handle "@ throw" correctly.
1927 const char *wBuf = strchr(startBuf, 'w');
1928 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1929 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1930
1931 const char *semiBuf = strchr(startBuf, ';');
1932 assert((*semiBuf == ';') && "@throw: can't find ';'");
1933 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001934 if (S->getThrowExpr())
1935 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001936 return 0;
1937}
1938
1939Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1940 // Create a new string expression.
1941 QualType StrType = Context->getPointerType(Context->CharTy);
1942 std::string StrEncoding;
1943 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1944 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1945 StringLiteral::Ascii, false,
1946 StrType, SourceLocation());
1947 ReplaceStmt(Exp, Replacement);
1948
1949 // Replace this subexpr in the parent.
1950 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1951 return Replacement;
1952}
1953
1954Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1955 if (!SelGetUidFunctionDecl)
1956 SynthSelGetUidFunctionDecl();
1957 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1958 // Create a call to sel_registerName("selName").
1959 SmallVector<Expr*, 8> SelExprs;
1960 QualType argType = Context->getPointerType(Context->CharTy);
1961 SelExprs.push_back(StringLiteral::Create(*Context,
1962 Exp->getSelector().getAsString(),
1963 StringLiteral::Ascii, false,
1964 argType, SourceLocation()));
1965 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1966 &SelExprs[0], SelExprs.size());
1967 ReplaceStmt(Exp, SelExp);
1968 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1969 return SelExp;
1970}
1971
1972CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1973 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1974 SourceLocation EndLoc) {
1975 // Get the type, we will need to reference it in a couple spots.
1976 QualType msgSendType = FD->getType();
1977
1978 // Create a reference to the objc_msgSend() declaration.
1979 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001980 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001981
1982 // Now, we cast the reference to a pointer to the objc_msgSend type.
1983 QualType pToFunc = Context->getPointerType(msgSendType);
1984 ImplicitCastExpr *ICE =
1985 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1986 DRE, 0, VK_RValue);
1987
1988 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1989
1990 CallExpr *Exp =
1991 new (Context) CallExpr(*Context, ICE, args, nargs,
1992 FT->getCallResultType(*Context),
1993 VK_RValue, EndLoc);
1994 return Exp;
1995}
1996
1997static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1998 const char *&startRef, const char *&endRef) {
1999 while (startBuf < endBuf) {
2000 if (*startBuf == '<')
2001 startRef = startBuf; // mark the start.
2002 if (*startBuf == '>') {
2003 if (startRef && *startRef == '<') {
2004 endRef = startBuf; // mark the end.
2005 return true;
2006 }
2007 return false;
2008 }
2009 startBuf++;
2010 }
2011 return false;
2012}
2013
2014static void scanToNextArgument(const char *&argRef) {
2015 int angle = 0;
2016 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2017 if (*argRef == '<')
2018 angle++;
2019 else if (*argRef == '>')
2020 angle--;
2021 argRef++;
2022 }
2023 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2024}
2025
2026bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2027 if (T->isObjCQualifiedIdType())
2028 return true;
2029 if (const PointerType *PT = T->getAs<PointerType>()) {
2030 if (PT->getPointeeType()->isObjCQualifiedIdType())
2031 return true;
2032 }
2033 if (T->isObjCObjectPointerType()) {
2034 T = T->getPointeeType();
2035 return T->isObjCQualifiedInterfaceType();
2036 }
2037 if (T->isArrayType()) {
2038 QualType ElemTy = Context->getBaseElementType(T);
2039 return needToScanForQualifiers(ElemTy);
2040 }
2041 return false;
2042}
2043
2044void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2045 QualType Type = E->getType();
2046 if (needToScanForQualifiers(Type)) {
2047 SourceLocation Loc, EndLoc;
2048
2049 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2050 Loc = ECE->getLParenLoc();
2051 EndLoc = ECE->getRParenLoc();
2052 } else {
2053 Loc = E->getLocStart();
2054 EndLoc = E->getLocEnd();
2055 }
2056 // This will defend against trying to rewrite synthesized expressions.
2057 if (Loc.isInvalid() || EndLoc.isInvalid())
2058 return;
2059
2060 const char *startBuf = SM->getCharacterData(Loc);
2061 const char *endBuf = SM->getCharacterData(EndLoc);
2062 const char *startRef = 0, *endRef = 0;
2063 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2064 // Get the locations of the startRef, endRef.
2065 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2066 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2067 // Comment out the protocol references.
2068 InsertText(LessLoc, "/*");
2069 InsertText(GreaterLoc, "*/");
2070 }
2071 }
2072}
2073
2074void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2075 SourceLocation Loc;
2076 QualType Type;
2077 const FunctionProtoType *proto = 0;
2078 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2079 Loc = VD->getLocation();
2080 Type = VD->getType();
2081 }
2082 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2083 Loc = FD->getLocation();
2084 // Check for ObjC 'id' and class types that have been adorned with protocol
2085 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2086 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2087 assert(funcType && "missing function type");
2088 proto = dyn_cast<FunctionProtoType>(funcType);
2089 if (!proto)
2090 return;
2091 Type = proto->getResultType();
2092 }
2093 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2094 Loc = FD->getLocation();
2095 Type = FD->getType();
2096 }
2097 else
2098 return;
2099
2100 if (needToScanForQualifiers(Type)) {
2101 // Since types are unique, we need to scan the buffer.
2102
2103 const char *endBuf = SM->getCharacterData(Loc);
2104 const char *startBuf = endBuf;
2105 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2106 startBuf--; // scan backward (from the decl location) for return type.
2107 const char *startRef = 0, *endRef = 0;
2108 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2109 // Get the locations of the startRef, endRef.
2110 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2111 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2112 // Comment out the protocol references.
2113 InsertText(LessLoc, "/*");
2114 InsertText(GreaterLoc, "*/");
2115 }
2116 }
2117 if (!proto)
2118 return; // most likely, was a variable
2119 // Now check arguments.
2120 const char *startBuf = SM->getCharacterData(Loc);
2121 const char *startFuncBuf = startBuf;
2122 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2123 if (needToScanForQualifiers(proto->getArgType(i))) {
2124 // Since types are unique, we need to scan the buffer.
2125
2126 const char *endBuf = startBuf;
2127 // scan forward (from the decl location) for argument types.
2128 scanToNextArgument(endBuf);
2129 const char *startRef = 0, *endRef = 0;
2130 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2131 // Get the locations of the startRef, endRef.
2132 SourceLocation LessLoc =
2133 Loc.getLocWithOffset(startRef-startFuncBuf);
2134 SourceLocation GreaterLoc =
2135 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2136 // Comment out the protocol references.
2137 InsertText(LessLoc, "/*");
2138 InsertText(GreaterLoc, "*/");
2139 }
2140 startBuf = ++endBuf;
2141 }
2142 else {
2143 // If the function name is derived from a macro expansion, then the
2144 // argument buffer will not follow the name. Need to speak with Chris.
2145 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2146 startBuf++; // scan forward (from the decl location) for argument types.
2147 startBuf++;
2148 }
2149 }
2150}
2151
2152void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2153 QualType QT = ND->getType();
2154 const Type* TypePtr = QT->getAs<Type>();
2155 if (!isa<TypeOfExprType>(TypePtr))
2156 return;
2157 while (isa<TypeOfExprType>(TypePtr)) {
2158 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2159 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2160 TypePtr = QT->getAs<Type>();
2161 }
2162 // FIXME. This will not work for multiple declarators; as in:
2163 // __typeof__(a) b,c,d;
2164 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2165 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2166 const char *startBuf = SM->getCharacterData(DeclLoc);
2167 if (ND->getInit()) {
2168 std::string Name(ND->getNameAsString());
2169 TypeAsString += " " + Name + " = ";
2170 Expr *E = ND->getInit();
2171 SourceLocation startLoc;
2172 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2173 startLoc = ECE->getLParenLoc();
2174 else
2175 startLoc = E->getLocStart();
2176 startLoc = SM->getExpansionLoc(startLoc);
2177 const char *endBuf = SM->getCharacterData(startLoc);
2178 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2179 }
2180 else {
2181 SourceLocation X = ND->getLocEnd();
2182 X = SM->getExpansionLoc(X);
2183 const char *endBuf = SM->getCharacterData(X);
2184 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2185 }
2186}
2187
2188// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2189void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2190 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2191 SmallVector<QualType, 16> ArgTys;
2192 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2193 QualType getFuncType =
2194 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2195 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2196 SourceLocation(),
2197 SourceLocation(),
2198 SelGetUidIdent, getFuncType, 0,
2199 SC_Extern,
2200 SC_None, false);
2201}
2202
2203void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2204 // declared in <objc/objc.h>
2205 if (FD->getIdentifier() &&
2206 FD->getName() == "sel_registerName") {
2207 SelGetUidFunctionDecl = FD;
2208 return;
2209 }
2210 RewriteObjCQualifiedInterfaceTypes(FD);
2211}
2212
2213void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2214 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2215 const char *argPtr = TypeString.c_str();
2216 if (!strchr(argPtr, '^')) {
2217 Str += TypeString;
2218 return;
2219 }
2220 while (*argPtr) {
2221 Str += (*argPtr == '^' ? '*' : *argPtr);
2222 argPtr++;
2223 }
2224}
2225
2226// FIXME. Consolidate this routine with RewriteBlockPointerType.
2227void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2228 ValueDecl *VD) {
2229 QualType Type = VD->getType();
2230 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2231 const char *argPtr = TypeString.c_str();
2232 int paren = 0;
2233 while (*argPtr) {
2234 switch (*argPtr) {
2235 case '(':
2236 Str += *argPtr;
2237 paren++;
2238 break;
2239 case ')':
2240 Str += *argPtr;
2241 paren--;
2242 break;
2243 case '^':
2244 Str += '*';
2245 if (paren == 1)
2246 Str += VD->getNameAsString();
2247 break;
2248 default:
2249 Str += *argPtr;
2250 break;
2251 }
2252 argPtr++;
2253 }
2254}
2255
2256
2257void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2258 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2259 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2260 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2261 if (!proto)
2262 return;
2263 QualType Type = proto->getResultType();
2264 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2265 FdStr += " ";
2266 FdStr += FD->getName();
2267 FdStr += "(";
2268 unsigned numArgs = proto->getNumArgs();
2269 for (unsigned i = 0; i < numArgs; i++) {
2270 QualType ArgType = proto->getArgType(i);
2271 RewriteBlockPointerType(FdStr, ArgType);
2272 if (i+1 < numArgs)
2273 FdStr += ", ";
2274 }
2275 FdStr += ");\n";
2276 InsertText(FunLocStart, FdStr);
2277 CurFunctionDeclToDeclareForBlock = 0;
2278}
2279
2280// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2281void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2282 if (SuperContructorFunctionDecl)
2283 return;
2284 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2285 SmallVector<QualType, 16> ArgTys;
2286 QualType argT = Context->getObjCIdType();
2287 assert(!argT.isNull() && "Can't find 'id' type");
2288 ArgTys.push_back(argT);
2289 ArgTys.push_back(argT);
2290 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2291 &ArgTys[0], ArgTys.size());
2292 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2293 SourceLocation(),
2294 SourceLocation(),
2295 msgSendIdent, msgSendType, 0,
2296 SC_Extern,
2297 SC_None, false);
2298}
2299
2300// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2301void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2302 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2303 SmallVector<QualType, 16> ArgTys;
2304 QualType argT = Context->getObjCIdType();
2305 assert(!argT.isNull() && "Can't find 'id' type");
2306 ArgTys.push_back(argT);
2307 argT = Context->getObjCSelType();
2308 assert(!argT.isNull() && "Can't find 'SEL' type");
2309 ArgTys.push_back(argT);
2310 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2311 &ArgTys[0], ArgTys.size(),
2312 true /*isVariadic*/);
2313 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2314 SourceLocation(),
2315 SourceLocation(),
2316 msgSendIdent, msgSendType, 0,
2317 SC_Extern,
2318 SC_None, false);
2319}
2320
2321// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2322void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2323 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2324 SmallVector<QualType, 16> ArgTys;
2325 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2326 SourceLocation(), SourceLocation(),
2327 &Context->Idents.get("objc_super"));
2328 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2329 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2330 ArgTys.push_back(argT);
2331 argT = Context->getObjCSelType();
2332 assert(!argT.isNull() && "Can't find 'SEL' type");
2333 ArgTys.push_back(argT);
2334 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2335 &ArgTys[0], ArgTys.size(),
2336 true /*isVariadic*/);
2337 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2338 SourceLocation(),
2339 SourceLocation(),
2340 msgSendIdent, msgSendType, 0,
2341 SC_Extern,
2342 SC_None, false);
2343}
2344
2345// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2346void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2347 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2348 SmallVector<QualType, 16> ArgTys;
2349 QualType argT = Context->getObjCIdType();
2350 assert(!argT.isNull() && "Can't find 'id' type");
2351 ArgTys.push_back(argT);
2352 argT = Context->getObjCSelType();
2353 assert(!argT.isNull() && "Can't find 'SEL' type");
2354 ArgTys.push_back(argT);
2355 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2356 &ArgTys[0], ArgTys.size(),
2357 true /*isVariadic*/);
2358 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2359 SourceLocation(),
2360 SourceLocation(),
2361 msgSendIdent, msgSendType, 0,
2362 SC_Extern,
2363 SC_None, false);
2364}
2365
2366// SynthMsgSendSuperStretFunctionDecl -
2367// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2368void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2369 IdentifierInfo *msgSendIdent =
2370 &Context->Idents.get("objc_msgSendSuper_stret");
2371 SmallVector<QualType, 16> ArgTys;
2372 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2373 SourceLocation(), SourceLocation(),
2374 &Context->Idents.get("objc_super"));
2375 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2376 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2377 ArgTys.push_back(argT);
2378 argT = Context->getObjCSelType();
2379 assert(!argT.isNull() && "Can't find 'SEL' type");
2380 ArgTys.push_back(argT);
2381 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2382 &ArgTys[0], ArgTys.size(),
2383 true /*isVariadic*/);
2384 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2385 SourceLocation(),
2386 SourceLocation(),
2387 msgSendIdent, msgSendType, 0,
2388 SC_Extern,
2389 SC_None, false);
2390}
2391
2392// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2393void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2394 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2395 SmallVector<QualType, 16> ArgTys;
2396 QualType argT = Context->getObjCIdType();
2397 assert(!argT.isNull() && "Can't find 'id' type");
2398 ArgTys.push_back(argT);
2399 argT = Context->getObjCSelType();
2400 assert(!argT.isNull() && "Can't find 'SEL' type");
2401 ArgTys.push_back(argT);
2402 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2403 &ArgTys[0], ArgTys.size(),
2404 true /*isVariadic*/);
2405 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2406 SourceLocation(),
2407 SourceLocation(),
2408 msgSendIdent, msgSendType, 0,
2409 SC_Extern,
2410 SC_None, false);
2411}
2412
2413// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2414void RewriteModernObjC::SynthGetClassFunctionDecl() {
2415 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2416 SmallVector<QualType, 16> ArgTys;
2417 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2418 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2419 &ArgTys[0], ArgTys.size());
2420 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2421 SourceLocation(),
2422 SourceLocation(),
2423 getClassIdent, getClassType, 0,
2424 SC_Extern,
2425 SC_None, false);
2426}
2427
2428// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2429void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2430 IdentifierInfo *getSuperClassIdent =
2431 &Context->Idents.get("class_getSuperclass");
2432 SmallVector<QualType, 16> ArgTys;
2433 ArgTys.push_back(Context->getObjCClassType());
2434 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2435 &ArgTys[0], ArgTys.size());
2436 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2437 SourceLocation(),
2438 SourceLocation(),
2439 getSuperClassIdent,
2440 getClassType, 0,
2441 SC_Extern,
2442 SC_None,
2443 false);
2444}
2445
2446// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2447void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2448 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2449 SmallVector<QualType, 16> ArgTys;
2450 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2451 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2452 &ArgTys[0], ArgTys.size());
2453 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2454 SourceLocation(),
2455 SourceLocation(),
2456 getClassIdent, getClassType, 0,
2457 SC_Extern,
2458 SC_None, false);
2459}
2460
2461Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2462 QualType strType = getConstantStringStructType();
2463
2464 std::string S = "__NSConstantStringImpl_";
2465
2466 std::string tmpName = InFileName;
2467 unsigned i;
2468 for (i=0; i < tmpName.length(); i++) {
2469 char c = tmpName.at(i);
2470 // replace any non alphanumeric characters with '_'.
2471 if (!isalpha(c) && (c < '0' || c > '9'))
2472 tmpName[i] = '_';
2473 }
2474 S += tmpName;
2475 S += "_";
2476 S += utostr(NumObjCStringLiterals++);
2477
2478 Preamble += "static __NSConstantStringImpl " + S;
2479 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2480 Preamble += "0x000007c8,"; // utf8_str
2481 // The pretty printer for StringLiteral handles escape characters properly.
2482 std::string prettyBufS;
2483 llvm::raw_string_ostream prettyBuf(prettyBufS);
2484 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2485 PrintingPolicy(LangOpts));
2486 Preamble += prettyBuf.str();
2487 Preamble += ",";
2488 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2489
2490 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2491 SourceLocation(), &Context->Idents.get(S),
2492 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002493 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002494 SourceLocation());
2495 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2496 Context->getPointerType(DRE->getType()),
2497 VK_RValue, OK_Ordinary,
2498 SourceLocation());
2499 // cast to NSConstantString *
2500 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2501 CK_CPointerToObjCPointerCast, Unop);
2502 ReplaceStmt(Exp, cast);
2503 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2504 return cast;
2505}
2506
2507// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2508QualType RewriteModernObjC::getSuperStructType() {
2509 if (!SuperStructDecl) {
2510 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2511 SourceLocation(), SourceLocation(),
2512 &Context->Idents.get("objc_super"));
2513 QualType FieldTypes[2];
2514
2515 // struct objc_object *receiver;
2516 FieldTypes[0] = Context->getObjCIdType();
2517 // struct objc_class *super;
2518 FieldTypes[1] = Context->getObjCClassType();
2519
2520 // Create fields
2521 for (unsigned i = 0; i < 2; ++i) {
2522 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2523 SourceLocation(),
2524 SourceLocation(), 0,
2525 FieldTypes[i], 0,
2526 /*BitWidth=*/0,
2527 /*Mutable=*/false,
2528 /*HasInit=*/false));
2529 }
2530
2531 SuperStructDecl->completeDefinition();
2532 }
2533 return Context->getTagDeclType(SuperStructDecl);
2534}
2535
2536QualType RewriteModernObjC::getConstantStringStructType() {
2537 if (!ConstantStringDecl) {
2538 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2539 SourceLocation(), SourceLocation(),
2540 &Context->Idents.get("__NSConstantStringImpl"));
2541 QualType FieldTypes[4];
2542
2543 // struct objc_object *receiver;
2544 FieldTypes[0] = Context->getObjCIdType();
2545 // int flags;
2546 FieldTypes[1] = Context->IntTy;
2547 // char *str;
2548 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2549 // long length;
2550 FieldTypes[3] = Context->LongTy;
2551
2552 // Create fields
2553 for (unsigned i = 0; i < 4; ++i) {
2554 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2555 ConstantStringDecl,
2556 SourceLocation(),
2557 SourceLocation(), 0,
2558 FieldTypes[i], 0,
2559 /*BitWidth=*/0,
2560 /*Mutable=*/true,
2561 /*HasInit=*/false));
2562 }
2563
2564 ConstantStringDecl->completeDefinition();
2565 }
2566 return Context->getTagDeclType(ConstantStringDecl);
2567}
2568
2569Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2570 SourceLocation StartLoc,
2571 SourceLocation EndLoc) {
2572 if (!SelGetUidFunctionDecl)
2573 SynthSelGetUidFunctionDecl();
2574 if (!MsgSendFunctionDecl)
2575 SynthMsgSendFunctionDecl();
2576 if (!MsgSendSuperFunctionDecl)
2577 SynthMsgSendSuperFunctionDecl();
2578 if (!MsgSendStretFunctionDecl)
2579 SynthMsgSendStretFunctionDecl();
2580 if (!MsgSendSuperStretFunctionDecl)
2581 SynthMsgSendSuperStretFunctionDecl();
2582 if (!MsgSendFpretFunctionDecl)
2583 SynthMsgSendFpretFunctionDecl();
2584 if (!GetClassFunctionDecl)
2585 SynthGetClassFunctionDecl();
2586 if (!GetSuperClassFunctionDecl)
2587 SynthGetSuperClassFunctionDecl();
2588 if (!GetMetaClassFunctionDecl)
2589 SynthGetMetaClassFunctionDecl();
2590
2591 // default to objc_msgSend().
2592 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2593 // May need to use objc_msgSend_stret() as well.
2594 FunctionDecl *MsgSendStretFlavor = 0;
2595 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2596 QualType resultType = mDecl->getResultType();
2597 if (resultType->isRecordType())
2598 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2599 else if (resultType->isRealFloatingType())
2600 MsgSendFlavor = MsgSendFpretFunctionDecl;
2601 }
2602
2603 // Synthesize a call to objc_msgSend().
2604 SmallVector<Expr*, 8> MsgExprs;
2605 switch (Exp->getReceiverKind()) {
2606 case ObjCMessageExpr::SuperClass: {
2607 MsgSendFlavor = MsgSendSuperFunctionDecl;
2608 if (MsgSendStretFlavor)
2609 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2610 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2611
2612 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2613
2614 SmallVector<Expr*, 4> InitExprs;
2615
2616 // set the receiver to self, the first argument to all methods.
2617 InitExprs.push_back(
2618 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2619 CK_BitCast,
2620 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002621 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002622 Context->getObjCIdType(),
2623 VK_RValue,
2624 SourceLocation()))
2625 ); // set the 'receiver'.
2626
2627 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2628 SmallVector<Expr*, 8> ClsExprs;
2629 QualType argType = Context->getPointerType(Context->CharTy);
2630 ClsExprs.push_back(StringLiteral::Create(*Context,
2631 ClassDecl->getIdentifier()->getName(),
2632 StringLiteral::Ascii, false,
2633 argType, SourceLocation()));
2634 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2635 &ClsExprs[0],
2636 ClsExprs.size(),
2637 StartLoc,
2638 EndLoc);
2639 // (Class)objc_getClass("CurrentClass")
2640 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2641 Context->getObjCClassType(),
2642 CK_BitCast, Cls);
2643 ClsExprs.clear();
2644 ClsExprs.push_back(ArgExpr);
2645 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2646 &ClsExprs[0], ClsExprs.size(),
2647 StartLoc, EndLoc);
2648
2649 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2650 // To turn off a warning, type-cast to 'id'
2651 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2652 NoTypeInfoCStyleCastExpr(Context,
2653 Context->getObjCIdType(),
2654 CK_BitCast, Cls));
2655 // struct objc_super
2656 QualType superType = getSuperStructType();
2657 Expr *SuperRep;
2658
2659 if (LangOpts.MicrosoftExt) {
2660 SynthSuperContructorFunctionDecl();
2661 // Simulate a contructor call...
2662 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002663 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002664 SourceLocation());
2665 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2666 InitExprs.size(),
2667 superType, VK_LValue,
2668 SourceLocation());
2669 // The code for super is a little tricky to prevent collision with
2670 // the structure definition in the header. The rewriter has it's own
2671 // internal definition (__rw_objc_super) that is uses. This is why
2672 // we need the cast below. For example:
2673 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2674 //
2675 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2676 Context->getPointerType(SuperRep->getType()),
2677 VK_RValue, OK_Ordinary,
2678 SourceLocation());
2679 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2680 Context->getPointerType(superType),
2681 CK_BitCast, SuperRep);
2682 } else {
2683 // (struct objc_super) { <exprs from above> }
2684 InitListExpr *ILE =
2685 new (Context) InitListExpr(*Context, SourceLocation(),
2686 &InitExprs[0], InitExprs.size(),
2687 SourceLocation());
2688 TypeSourceInfo *superTInfo
2689 = Context->getTrivialTypeSourceInfo(superType);
2690 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2691 superType, VK_LValue,
2692 ILE, false);
2693 // struct objc_super *
2694 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2695 Context->getPointerType(SuperRep->getType()),
2696 VK_RValue, OK_Ordinary,
2697 SourceLocation());
2698 }
2699 MsgExprs.push_back(SuperRep);
2700 break;
2701 }
2702
2703 case ObjCMessageExpr::Class: {
2704 SmallVector<Expr*, 8> ClsExprs;
2705 QualType argType = Context->getPointerType(Context->CharTy);
2706 ObjCInterfaceDecl *Class
2707 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2708 IdentifierInfo *clsName = Class->getIdentifier();
2709 ClsExprs.push_back(StringLiteral::Create(*Context,
2710 clsName->getName(),
2711 StringLiteral::Ascii, false,
2712 argType, SourceLocation()));
2713 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2714 &ClsExprs[0],
2715 ClsExprs.size(),
2716 StartLoc, EndLoc);
2717 MsgExprs.push_back(Cls);
2718 break;
2719 }
2720
2721 case ObjCMessageExpr::SuperInstance:{
2722 MsgSendFlavor = MsgSendSuperFunctionDecl;
2723 if (MsgSendStretFlavor)
2724 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2725 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2726 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2727 SmallVector<Expr*, 4> InitExprs;
2728
2729 InitExprs.push_back(
2730 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2731 CK_BitCast,
2732 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002733 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002734 Context->getObjCIdType(),
2735 VK_RValue, SourceLocation()))
2736 ); // set the 'receiver'.
2737
2738 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2739 SmallVector<Expr*, 8> ClsExprs;
2740 QualType argType = Context->getPointerType(Context->CharTy);
2741 ClsExprs.push_back(StringLiteral::Create(*Context,
2742 ClassDecl->getIdentifier()->getName(),
2743 StringLiteral::Ascii, false, argType,
2744 SourceLocation()));
2745 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2746 &ClsExprs[0],
2747 ClsExprs.size(),
2748 StartLoc, EndLoc);
2749 // (Class)objc_getClass("CurrentClass")
2750 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2751 Context->getObjCClassType(),
2752 CK_BitCast, Cls);
2753 ClsExprs.clear();
2754 ClsExprs.push_back(ArgExpr);
2755 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2756 &ClsExprs[0], ClsExprs.size(),
2757 StartLoc, EndLoc);
2758
2759 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2760 // To turn off a warning, type-cast to 'id'
2761 InitExprs.push_back(
2762 // set 'super class', using class_getSuperclass().
2763 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2764 CK_BitCast, Cls));
2765 // struct objc_super
2766 QualType superType = getSuperStructType();
2767 Expr *SuperRep;
2768
2769 if (LangOpts.MicrosoftExt) {
2770 SynthSuperContructorFunctionDecl();
2771 // Simulate a contructor call...
2772 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002773 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002774 SourceLocation());
2775 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2776 InitExprs.size(),
2777 superType, VK_LValue, SourceLocation());
2778 // The code for super is a little tricky to prevent collision with
2779 // the structure definition in the header. The rewriter has it's own
2780 // internal definition (__rw_objc_super) that is uses. This is why
2781 // we need the cast below. For example:
2782 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2783 //
2784 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2785 Context->getPointerType(SuperRep->getType()),
2786 VK_RValue, OK_Ordinary,
2787 SourceLocation());
2788 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2789 Context->getPointerType(superType),
2790 CK_BitCast, SuperRep);
2791 } else {
2792 // (struct objc_super) { <exprs from above> }
2793 InitListExpr *ILE =
2794 new (Context) InitListExpr(*Context, SourceLocation(),
2795 &InitExprs[0], InitExprs.size(),
2796 SourceLocation());
2797 TypeSourceInfo *superTInfo
2798 = Context->getTrivialTypeSourceInfo(superType);
2799 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2800 superType, VK_RValue, ILE,
2801 false);
2802 }
2803 MsgExprs.push_back(SuperRep);
2804 break;
2805 }
2806
2807 case ObjCMessageExpr::Instance: {
2808 // Remove all type-casts because it may contain objc-style types; e.g.
2809 // Foo<Proto> *.
2810 Expr *recExpr = Exp->getInstanceReceiver();
2811 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2812 recExpr = CE->getSubExpr();
2813 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2814 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2815 ? CK_BlockPointerToObjCPointerCast
2816 : CK_CPointerToObjCPointerCast;
2817
2818 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2819 CK, recExpr);
2820 MsgExprs.push_back(recExpr);
2821 break;
2822 }
2823 }
2824
2825 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2826 SmallVector<Expr*, 8> SelExprs;
2827 QualType argType = Context->getPointerType(Context->CharTy);
2828 SelExprs.push_back(StringLiteral::Create(*Context,
2829 Exp->getSelector().getAsString(),
2830 StringLiteral::Ascii, false,
2831 argType, SourceLocation()));
2832 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2833 &SelExprs[0], SelExprs.size(),
2834 StartLoc,
2835 EndLoc);
2836 MsgExprs.push_back(SelExp);
2837
2838 // Now push any user supplied arguments.
2839 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2840 Expr *userExpr = Exp->getArg(i);
2841 // Make all implicit casts explicit...ICE comes in handy:-)
2842 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2843 // Reuse the ICE type, it is exactly what the doctor ordered.
2844 QualType type = ICE->getType();
2845 if (needToScanForQualifiers(type))
2846 type = Context->getObjCIdType();
2847 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2848 (void)convertBlockPointerToFunctionPointer(type);
2849 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2850 CastKind CK;
2851 if (SubExpr->getType()->isIntegralType(*Context) &&
2852 type->isBooleanType()) {
2853 CK = CK_IntegralToBoolean;
2854 } else if (type->isObjCObjectPointerType()) {
2855 if (SubExpr->getType()->isBlockPointerType()) {
2856 CK = CK_BlockPointerToObjCPointerCast;
2857 } else if (SubExpr->getType()->isPointerType()) {
2858 CK = CK_CPointerToObjCPointerCast;
2859 } else {
2860 CK = CK_BitCast;
2861 }
2862 } else {
2863 CK = CK_BitCast;
2864 }
2865
2866 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2867 }
2868 // Make id<P...> cast into an 'id' cast.
2869 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2870 if (CE->getType()->isObjCQualifiedIdType()) {
2871 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2872 userExpr = CE->getSubExpr();
2873 CastKind CK;
2874 if (userExpr->getType()->isIntegralType(*Context)) {
2875 CK = CK_IntegralToPointer;
2876 } else if (userExpr->getType()->isBlockPointerType()) {
2877 CK = CK_BlockPointerToObjCPointerCast;
2878 } else if (userExpr->getType()->isPointerType()) {
2879 CK = CK_CPointerToObjCPointerCast;
2880 } else {
2881 CK = CK_BitCast;
2882 }
2883 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2884 CK, userExpr);
2885 }
2886 }
2887 MsgExprs.push_back(userExpr);
2888 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2889 // out the argument in the original expression (since we aren't deleting
2890 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2891 //Exp->setArg(i, 0);
2892 }
2893 // Generate the funky cast.
2894 CastExpr *cast;
2895 SmallVector<QualType, 8> ArgTypes;
2896 QualType returnType;
2897
2898 // Push 'id' and 'SEL', the 2 implicit arguments.
2899 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2900 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2901 else
2902 ArgTypes.push_back(Context->getObjCIdType());
2903 ArgTypes.push_back(Context->getObjCSelType());
2904 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2905 // Push any user argument types.
2906 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2907 E = OMD->param_end(); PI != E; ++PI) {
2908 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2909 ? Context->getObjCIdType()
2910 : (*PI)->getType();
2911 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2912 (void)convertBlockPointerToFunctionPointer(t);
2913 ArgTypes.push_back(t);
2914 }
2915 returnType = Exp->getType();
2916 convertToUnqualifiedObjCType(returnType);
2917 (void)convertBlockPointerToFunctionPointer(returnType);
2918 } else {
2919 returnType = Context->getObjCIdType();
2920 }
2921 // Get the type, we will need to reference it in a couple spots.
2922 QualType msgSendType = MsgSendFlavor->getType();
2923
2924 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002925 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002926 VK_LValue, SourceLocation());
2927
2928 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2929 // If we don't do this cast, we get the following bizarre warning/note:
2930 // xx.m:13: warning: function called through a non-compatible type
2931 // xx.m:13: note: if this code is reached, the program will abort
2932 cast = NoTypeInfoCStyleCastExpr(Context,
2933 Context->getPointerType(Context->VoidTy),
2934 CK_BitCast, DRE);
2935
2936 // Now do the "normal" pointer to function cast.
2937 QualType castType =
2938 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2939 // If we don't have a method decl, force a variadic cast.
2940 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2941 castType = Context->getPointerType(castType);
2942 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2943 cast);
2944
2945 // Don't forget the parens to enforce the proper binding.
2946 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2947
2948 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2949 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2950 MsgExprs.size(),
2951 FT->getResultType(), VK_RValue,
2952 EndLoc);
2953 Stmt *ReplacingStmt = CE;
2954 if (MsgSendStretFlavor) {
2955 // We have the method which returns a struct/union. Must also generate
2956 // call to objc_msgSend_stret and hang both varieties on a conditional
2957 // expression which dictate which one to envoke depending on size of
2958 // method's return type.
2959
2960 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002961 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2962 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002963 VK_LValue, SourceLocation());
2964 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2965 cast = NoTypeInfoCStyleCastExpr(Context,
2966 Context->getPointerType(Context->VoidTy),
2967 CK_BitCast, STDRE);
2968 // Now do the "normal" pointer to function cast.
2969 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2970 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2971 castType = Context->getPointerType(castType);
2972 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2973 cast);
2974
2975 // Don't forget the parens to enforce the proper binding.
2976 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2977
2978 FT = msgSendType->getAs<FunctionType>();
2979 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2980 MsgExprs.size(),
2981 FT->getResultType(), VK_RValue,
2982 SourceLocation());
2983
2984 // Build sizeof(returnType)
2985 UnaryExprOrTypeTraitExpr *sizeofExpr =
2986 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2987 Context->getTrivialTypeSourceInfo(returnType),
2988 Context->getSizeType(), SourceLocation(),
2989 SourceLocation());
2990 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2991 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2992 // For X86 it is more complicated and some kind of target specific routine
2993 // is needed to decide what to do.
2994 unsigned IntSize =
2995 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2996 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2997 llvm::APInt(IntSize, 8),
2998 Context->IntTy,
2999 SourceLocation());
3000 BinaryOperator *lessThanExpr =
3001 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3002 VK_RValue, OK_Ordinary, SourceLocation());
3003 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3004 ConditionalOperator *CondExpr =
3005 new (Context) ConditionalOperator(lessThanExpr,
3006 SourceLocation(), CE,
3007 SourceLocation(), STCE,
3008 returnType, VK_RValue, OK_Ordinary);
3009 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3010 CondExpr);
3011 }
3012 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3013 return ReplacingStmt;
3014}
3015
3016Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3017 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3018 Exp->getLocEnd());
3019
3020 // Now do the actual rewrite.
3021 ReplaceStmt(Exp, ReplacingStmt);
3022
3023 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3024 return ReplacingStmt;
3025}
3026
3027// typedef struct objc_object Protocol;
3028QualType RewriteModernObjC::getProtocolType() {
3029 if (!ProtocolTypeDecl) {
3030 TypeSourceInfo *TInfo
3031 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3032 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3033 SourceLocation(), SourceLocation(),
3034 &Context->Idents.get("Protocol"),
3035 TInfo);
3036 }
3037 return Context->getTypeDeclType(ProtocolTypeDecl);
3038}
3039
3040/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3041/// a synthesized/forward data reference (to the protocol's metadata).
3042/// The forward references (and metadata) are generated in
3043/// RewriteModernObjC::HandleTranslationUnit().
3044Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003045 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3046 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003047 IdentifierInfo *ID = &Context->Idents.get(Name);
3048 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3049 SourceLocation(), ID, getProtocolType(), 0,
3050 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003051 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3052 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003053 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3054 Context->getPointerType(DRE->getType()),
3055 VK_RValue, OK_Ordinary, SourceLocation());
3056 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3057 CK_BitCast,
3058 DerefExpr);
3059 ReplaceStmt(Exp, castExpr);
3060 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3061 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3062 return castExpr;
3063
3064}
3065
3066bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3067 const char *endBuf) {
3068 while (startBuf < endBuf) {
3069 if (*startBuf == '#') {
3070 // Skip whitespace.
3071 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3072 ;
3073 if (!strncmp(startBuf, "if", strlen("if")) ||
3074 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3075 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3076 !strncmp(startBuf, "define", strlen("define")) ||
3077 !strncmp(startBuf, "undef", strlen("undef")) ||
3078 !strncmp(startBuf, "else", strlen("else")) ||
3079 !strncmp(startBuf, "elif", strlen("elif")) ||
3080 !strncmp(startBuf, "endif", strlen("endif")) ||
3081 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3082 !strncmp(startBuf, "include", strlen("include")) ||
3083 !strncmp(startBuf, "import", strlen("import")) ||
3084 !strncmp(startBuf, "include_next", strlen("include_next")))
3085 return true;
3086 }
3087 startBuf++;
3088 }
3089 return false;
3090}
3091
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003092/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003093/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003094bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3095 std::string &Result) {
3096 if (Type->isArrayType()) {
3097 QualType ElemTy = Context->getBaseElementType(Type);
3098 return RewriteObjCFieldDeclType(ElemTy, Result);
3099 }
3100 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003101 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3102 if (RD->isCompleteDefinition()) {
3103 if (RD->isStruct())
3104 Result += "\n\tstruct ";
3105 else if (RD->isUnion())
3106 Result += "\n\tunion ";
3107 else
3108 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003109
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003110 Result += RD->getName();
3111 if (TagsDefinedInIvarDecls.count(RD)) {
3112 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003113 Result += " ";
3114 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003115 }
3116 TagsDefinedInIvarDecls.insert(RD);
3117 Result += " {\n";
3118 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003119 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003120 FieldDecl *FD = *i;
3121 RewriteObjCFieldDecl(FD, Result);
3122 }
3123 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003124 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003125 }
3126 }
3127 else if (Type->isEnumeralType()) {
3128 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3129 if (ED->isCompleteDefinition()) {
3130 Result += "\n\tenum ";
3131 Result += ED->getName();
3132 if (TagsDefinedInIvarDecls.count(ED)) {
3133 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003134 Result += " ";
3135 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003136 }
3137 TagsDefinedInIvarDecls.insert(ED);
3138
3139 Result += " {\n";
3140 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3141 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3142 Result += "\t"; Result += EC->getName(); Result += " = ";
3143 llvm::APSInt Val = EC->getInitVal();
3144 Result += Val.toString(10);
3145 Result += ",\n";
3146 }
3147 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003148 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003149 }
3150 }
3151
3152 Result += "\t";
3153 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003154 return false;
3155}
3156
3157
3158/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3159/// It handles elaborated types, as well as enum types in the process.
3160void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3161 std::string &Result) {
3162 QualType Type = fieldDecl->getType();
3163 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003164
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003165 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3166 if (!EleboratedType)
3167 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003168 Result += Name;
3169 if (fieldDecl->isBitField()) {
3170 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3171 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003172 else if (EleboratedType && Type->isArrayType()) {
3173 CanQualType CType = Context->getCanonicalType(Type);
3174 while (isa<ArrayType>(CType)) {
3175 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3176 Result += "[";
3177 llvm::APInt Dim = CAT->getSize();
3178 Result += utostr(Dim.getZExtValue());
3179 Result += "]";
3180 }
3181 CType = CType->getAs<ArrayType>()->getElementType();
3182 }
3183 }
3184
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003185 Result += ";\n";
3186}
3187
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003188/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3189/// an objective-c class with ivars.
3190void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3191 std::string &Result) {
3192 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3193 assert(CDecl->getName() != "" &&
3194 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003195 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003196 SmallVector<ObjCIvarDecl *, 8> IVars;
3197 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003198 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003199 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003200
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003201 SourceLocation LocStart = CDecl->getLocStart();
3202 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003203
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003204 const char *startBuf = SM->getCharacterData(LocStart);
3205 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003206
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003207 // If no ivars and no root or if its root, directly or indirectly,
3208 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003209 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003210 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3211 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3212 ReplaceText(LocStart, endBuf-startBuf, Result);
3213 return;
3214 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003215
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003216 Result += "\nstruct ";
3217 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003218 Result += "_IMPL {\n";
3219
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003220 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003221 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3222 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3223 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003224 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003225 TagsDefinedInIvarDecls.clear();
3226 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3227 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003228
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003229 Result += "};\n";
3230 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3231 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003232 // Mark this struct as having been generated.
3233 if (!ObjCSynthesizedStructs.insert(CDecl))
3234 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003235}
3236
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003237/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3238/// have been referenced in an ivar access expression.
3239void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3240 std::string &Result) {
3241 // write out ivar offset symbols which have been referenced in an ivar
3242 // access expression.
3243 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3244 if (Ivars.empty())
3245 return;
3246 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3247 e = Ivars.end(); i != e; i++) {
3248 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003249 Result += "\n";
3250 if (LangOpts.MicrosoftExt)
3251 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3252 if (LangOpts.MicrosoftExt &&
3253 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3254 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3255 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3256 if (CDecl->getImplementation())
3257 Result += "__declspec(dllexport) ";
3258 }
3259 Result += "extern unsigned long OBJC_IVAR_$_";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003260 Result += CDecl->getName(); Result += "_";
3261 Result += IvarDecl->getName(); Result += ";";
3262 }
3263}
3264
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003265//===----------------------------------------------------------------------===//
3266// Meta Data Emission
3267//===----------------------------------------------------------------------===//
3268
3269
3270/// RewriteImplementations - This routine rewrites all method implementations
3271/// and emits meta-data.
3272
3273void RewriteModernObjC::RewriteImplementations() {
3274 int ClsDefCount = ClassImplementation.size();
3275 int CatDefCount = CategoryImplementation.size();
3276
3277 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003278 for (int i = 0; i < ClsDefCount; i++) {
3279 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3280 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3281 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003282 assert(false &&
3283 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003284 RewriteImplementationDecl(OIMP);
3285 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003286
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003287 for (int i = 0; i < CatDefCount; i++) {
3288 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3289 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3290 if (CDecl->isImplicitInterfaceDecl())
3291 assert(false &&
3292 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003293 RewriteImplementationDecl(CIMP);
3294 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003295}
3296
3297void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3298 const std::string &Name,
3299 ValueDecl *VD, bool def) {
3300 assert(BlockByRefDeclNo.count(VD) &&
3301 "RewriteByRefString: ByRef decl missing");
3302 if (def)
3303 ResultStr += "struct ";
3304 ResultStr += "__Block_byref_" + Name +
3305 "_" + utostr(BlockByRefDeclNo[VD]) ;
3306}
3307
3308static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3309 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3310 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3311 return false;
3312}
3313
3314std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3315 StringRef funcName,
3316 std::string Tag) {
3317 const FunctionType *AFT = CE->getFunctionType();
3318 QualType RT = AFT->getResultType();
3319 std::string StructRef = "struct " + Tag;
3320 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3321 funcName.str() + "_" + "block_func_" + utostr(i);
3322
3323 BlockDecl *BD = CE->getBlockDecl();
3324
3325 if (isa<FunctionNoProtoType>(AFT)) {
3326 // No user-supplied arguments. Still need to pass in a pointer to the
3327 // block (to reference imported block decl refs).
3328 S += "(" + StructRef + " *__cself)";
3329 } else if (BD->param_empty()) {
3330 S += "(" + StructRef + " *__cself)";
3331 } else {
3332 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3333 assert(FT && "SynthesizeBlockFunc: No function proto");
3334 S += '(';
3335 // first add the implicit argument.
3336 S += StructRef + " *__cself, ";
3337 std::string ParamStr;
3338 for (BlockDecl::param_iterator AI = BD->param_begin(),
3339 E = BD->param_end(); AI != E; ++AI) {
3340 if (AI != BD->param_begin()) S += ", ";
3341 ParamStr = (*AI)->getNameAsString();
3342 QualType QT = (*AI)->getType();
3343 if (convertBlockPointerToFunctionPointer(QT))
3344 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3345 else
3346 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3347 S += ParamStr;
3348 }
3349 if (FT->isVariadic()) {
3350 if (!BD->param_empty()) S += ", ";
3351 S += "...";
3352 }
3353 S += ')';
3354 }
3355 S += " {\n";
3356
3357 // Create local declarations to avoid rewriting all closure decl ref exprs.
3358 // First, emit a declaration for all "by ref" decls.
3359 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3360 E = BlockByRefDecls.end(); I != E; ++I) {
3361 S += " ";
3362 std::string Name = (*I)->getNameAsString();
3363 std::string TypeString;
3364 RewriteByRefString(TypeString, Name, (*I));
3365 TypeString += " *";
3366 Name = TypeString + Name;
3367 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3368 }
3369 // Next, emit a declaration for all "by copy" declarations.
3370 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3371 E = BlockByCopyDecls.end(); I != E; ++I) {
3372 S += " ";
3373 // Handle nested closure invocation. For example:
3374 //
3375 // void (^myImportedClosure)(void);
3376 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3377 //
3378 // void (^anotherClosure)(void);
3379 // anotherClosure = ^(void) {
3380 // myImportedClosure(); // import and invoke the closure
3381 // };
3382 //
3383 if (isTopLevelBlockPointerType((*I)->getType())) {
3384 RewriteBlockPointerTypeVariable(S, (*I));
3385 S += " = (";
3386 RewriteBlockPointerType(S, (*I)->getType());
3387 S += ")";
3388 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3389 }
3390 else {
3391 std::string Name = (*I)->getNameAsString();
3392 QualType QT = (*I)->getType();
3393 if (HasLocalVariableExternalStorage(*I))
3394 QT = Context->getPointerType(QT);
3395 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3396 S += Name + " = __cself->" +
3397 (*I)->getNameAsString() + "; // bound by copy\n";
3398 }
3399 }
3400 std::string RewrittenStr = RewrittenBlockExprs[CE];
3401 const char *cstr = RewrittenStr.c_str();
3402 while (*cstr++ != '{') ;
3403 S += cstr;
3404 S += "\n";
3405 return S;
3406}
3407
3408std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3409 StringRef funcName,
3410 std::string Tag) {
3411 std::string StructRef = "struct " + Tag;
3412 std::string S = "static void __";
3413
3414 S += funcName;
3415 S += "_block_copy_" + utostr(i);
3416 S += "(" + StructRef;
3417 S += "*dst, " + StructRef;
3418 S += "*src) {";
3419 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3420 E = ImportedBlockDecls.end(); I != E; ++I) {
3421 ValueDecl *VD = (*I);
3422 S += "_Block_object_assign((void*)&dst->";
3423 S += (*I)->getNameAsString();
3424 S += ", (void*)src->";
3425 S += (*I)->getNameAsString();
3426 if (BlockByRefDeclsPtrSet.count((*I)))
3427 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3428 else if (VD->getType()->isBlockPointerType())
3429 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3430 else
3431 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3432 }
3433 S += "}\n";
3434
3435 S += "\nstatic void __";
3436 S += funcName;
3437 S += "_block_dispose_" + utostr(i);
3438 S += "(" + StructRef;
3439 S += "*src) {";
3440 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3441 E = ImportedBlockDecls.end(); I != E; ++I) {
3442 ValueDecl *VD = (*I);
3443 S += "_Block_object_dispose((void*)src->";
3444 S += (*I)->getNameAsString();
3445 if (BlockByRefDeclsPtrSet.count((*I)))
3446 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3447 else if (VD->getType()->isBlockPointerType())
3448 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3449 else
3450 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3451 }
3452 S += "}\n";
3453 return S;
3454}
3455
3456std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3457 std::string Desc) {
3458 std::string S = "\nstruct " + Tag;
3459 std::string Constructor = " " + Tag;
3460
3461 S += " {\n struct __block_impl impl;\n";
3462 S += " struct " + Desc;
3463 S += "* Desc;\n";
3464
3465 Constructor += "(void *fp, "; // Invoke function pointer.
3466 Constructor += "struct " + Desc; // Descriptor pointer.
3467 Constructor += " *desc";
3468
3469 if (BlockDeclRefs.size()) {
3470 // Output all "by copy" declarations.
3471 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3472 E = BlockByCopyDecls.end(); I != E; ++I) {
3473 S += " ";
3474 std::string FieldName = (*I)->getNameAsString();
3475 std::string ArgName = "_" + FieldName;
3476 // Handle nested closure invocation. For example:
3477 //
3478 // void (^myImportedBlock)(void);
3479 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3480 //
3481 // void (^anotherBlock)(void);
3482 // anotherBlock = ^(void) {
3483 // myImportedBlock(); // import and invoke the closure
3484 // };
3485 //
3486 if (isTopLevelBlockPointerType((*I)->getType())) {
3487 S += "struct __block_impl *";
3488 Constructor += ", void *" + ArgName;
3489 } else {
3490 QualType QT = (*I)->getType();
3491 if (HasLocalVariableExternalStorage(*I))
3492 QT = Context->getPointerType(QT);
3493 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3494 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3495 Constructor += ", " + ArgName;
3496 }
3497 S += FieldName + ";\n";
3498 }
3499 // Output all "by ref" declarations.
3500 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3501 E = BlockByRefDecls.end(); I != E; ++I) {
3502 S += " ";
3503 std::string FieldName = (*I)->getNameAsString();
3504 std::string ArgName = "_" + FieldName;
3505 {
3506 std::string TypeString;
3507 RewriteByRefString(TypeString, FieldName, (*I));
3508 TypeString += " *";
3509 FieldName = TypeString + FieldName;
3510 ArgName = TypeString + ArgName;
3511 Constructor += ", " + ArgName;
3512 }
3513 S += FieldName + "; // by ref\n";
3514 }
3515 // Finish writing the constructor.
3516 Constructor += ", int flags=0)";
3517 // Initialize all "by copy" arguments.
3518 bool firsTime = true;
3519 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3520 E = BlockByCopyDecls.end(); I != E; ++I) {
3521 std::string Name = (*I)->getNameAsString();
3522 if (firsTime) {
3523 Constructor += " : ";
3524 firsTime = false;
3525 }
3526 else
3527 Constructor += ", ";
3528 if (isTopLevelBlockPointerType((*I)->getType()))
3529 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3530 else
3531 Constructor += Name + "(_" + Name + ")";
3532 }
3533 // Initialize all "by ref" arguments.
3534 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3535 E = BlockByRefDecls.end(); I != E; ++I) {
3536 std::string Name = (*I)->getNameAsString();
3537 if (firsTime) {
3538 Constructor += " : ";
3539 firsTime = false;
3540 }
3541 else
3542 Constructor += ", ";
3543 Constructor += Name + "(_" + Name + "->__forwarding)";
3544 }
3545
3546 Constructor += " {\n";
3547 if (GlobalVarDecl)
3548 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3549 else
3550 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3551 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3552
3553 Constructor += " Desc = desc;\n";
3554 } else {
3555 // Finish writing the constructor.
3556 Constructor += ", int flags=0) {\n";
3557 if (GlobalVarDecl)
3558 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3559 else
3560 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3561 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3562 Constructor += " Desc = desc;\n";
3563 }
3564 Constructor += " ";
3565 Constructor += "}\n";
3566 S += Constructor;
3567 S += "};\n";
3568 return S;
3569}
3570
3571std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3572 std::string ImplTag, int i,
3573 StringRef FunName,
3574 unsigned hasCopy) {
3575 std::string S = "\nstatic struct " + DescTag;
3576
3577 S += " {\n unsigned long reserved;\n";
3578 S += " unsigned long Block_size;\n";
3579 if (hasCopy) {
3580 S += " void (*copy)(struct ";
3581 S += ImplTag; S += "*, struct ";
3582 S += ImplTag; S += "*);\n";
3583
3584 S += " void (*dispose)(struct ";
3585 S += ImplTag; S += "*);\n";
3586 }
3587 S += "} ";
3588
3589 S += DescTag + "_DATA = { 0, sizeof(struct ";
3590 S += ImplTag + ")";
3591 if (hasCopy) {
3592 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3593 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3594 }
3595 S += "};\n";
3596 return S;
3597}
3598
3599void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3600 StringRef FunName) {
3601 // Insert declaration for the function in which block literal is used.
3602 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3603 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3604 bool RewriteSC = (GlobalVarDecl &&
3605 !Blocks.empty() &&
3606 GlobalVarDecl->getStorageClass() == SC_Static &&
3607 GlobalVarDecl->getType().getCVRQualifiers());
3608 if (RewriteSC) {
3609 std::string SC(" void __");
3610 SC += GlobalVarDecl->getNameAsString();
3611 SC += "() {}";
3612 InsertText(FunLocStart, SC);
3613 }
3614
3615 // Insert closures that were part of the function.
3616 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3617 CollectBlockDeclRefInfo(Blocks[i]);
3618 // Need to copy-in the inner copied-in variables not actually used in this
3619 // block.
3620 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003621 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003622 ValueDecl *VD = Exp->getDecl();
3623 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003624 if (!VD->hasAttr<BlocksAttr>()) {
3625 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3626 BlockByCopyDeclsPtrSet.insert(VD);
3627 BlockByCopyDecls.push_back(VD);
3628 }
3629 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003630 }
John McCallf4b88a42012-03-10 09:33:50 +00003631
3632 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003633 BlockByRefDeclsPtrSet.insert(VD);
3634 BlockByRefDecls.push_back(VD);
3635 }
John McCallf4b88a42012-03-10 09:33:50 +00003636
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003637 // imported objects in the inner blocks not used in the outer
3638 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003639 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003640 VD->getType()->isBlockPointerType())
3641 ImportedBlockDecls.insert(VD);
3642 }
3643
3644 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3645 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3646
3647 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3648
3649 InsertText(FunLocStart, CI);
3650
3651 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3652
3653 InsertText(FunLocStart, CF);
3654
3655 if (ImportedBlockDecls.size()) {
3656 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3657 InsertText(FunLocStart, HF);
3658 }
3659 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3660 ImportedBlockDecls.size() > 0);
3661 InsertText(FunLocStart, BD);
3662
3663 BlockDeclRefs.clear();
3664 BlockByRefDecls.clear();
3665 BlockByRefDeclsPtrSet.clear();
3666 BlockByCopyDecls.clear();
3667 BlockByCopyDeclsPtrSet.clear();
3668 ImportedBlockDecls.clear();
3669 }
3670 if (RewriteSC) {
3671 // Must insert any 'const/volatile/static here. Since it has been
3672 // removed as result of rewriting of block literals.
3673 std::string SC;
3674 if (GlobalVarDecl->getStorageClass() == SC_Static)
3675 SC = "static ";
3676 if (GlobalVarDecl->getType().isConstQualified())
3677 SC += "const ";
3678 if (GlobalVarDecl->getType().isVolatileQualified())
3679 SC += "volatile ";
3680 if (GlobalVarDecl->getType().isRestrictQualified())
3681 SC += "restrict ";
3682 InsertText(FunLocStart, SC);
3683 }
3684
3685 Blocks.clear();
3686 InnerDeclRefsCount.clear();
3687 InnerDeclRefs.clear();
3688 RewrittenBlockExprs.clear();
3689}
3690
3691void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3692 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3693 StringRef FuncName = FD->getName();
3694
3695 SynthesizeBlockLiterals(FunLocStart, FuncName);
3696}
3697
3698static void BuildUniqueMethodName(std::string &Name,
3699 ObjCMethodDecl *MD) {
3700 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3701 Name = IFace->getName();
3702 Name += "__" + MD->getSelector().getAsString();
3703 // Convert colons to underscores.
3704 std::string::size_type loc = 0;
3705 while ((loc = Name.find(":", loc)) != std::string::npos)
3706 Name.replace(loc, 1, "_");
3707}
3708
3709void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3710 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3711 //SourceLocation FunLocStart = MD->getLocStart();
3712 SourceLocation FunLocStart = MD->getLocStart();
3713 std::string FuncName;
3714 BuildUniqueMethodName(FuncName, MD);
3715 SynthesizeBlockLiterals(FunLocStart, FuncName);
3716}
3717
3718void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3719 for (Stmt::child_range CI = S->children(); CI; ++CI)
3720 if (*CI) {
3721 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3722 GetBlockDeclRefExprs(CBE->getBody());
3723 else
3724 GetBlockDeclRefExprs(*CI);
3725 }
3726 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3728 if (DRE->refersToEnclosingLocal() &&
3729 HasLocalVariableExternalStorage(DRE->getDecl())) {
3730 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003731 }
3732
3733 return;
3734}
3735
3736void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003737 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003738 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3739 for (Stmt::child_range CI = S->children(); CI; ++CI)
3740 if (*CI) {
3741 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3742 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3743 GetInnerBlockDeclRefExprs(CBE->getBody(),
3744 InnerBlockDeclRefs,
3745 InnerContexts);
3746 }
3747 else
3748 GetInnerBlockDeclRefExprs(*CI,
3749 InnerBlockDeclRefs,
3750 InnerContexts);
3751
3752 }
3753 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3755 if (DRE->refersToEnclosingLocal()) {
3756 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3757 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3758 InnerBlockDeclRefs.push_back(DRE);
3759 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3760 if (Var->isFunctionOrMethodVarDecl())
3761 ImportedLocalExternalDecls.insert(Var);
3762 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003763 }
3764
3765 return;
3766}
3767
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003768/// convertObjCTypeToCStyleType - This routine converts such objc types
3769/// as qualified objects, and blocks to their closest c/c++ types that
3770/// it can. It returns true if input type was modified.
3771bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3772 QualType oldT = T;
3773 convertBlockPointerToFunctionPointer(T);
3774 if (T->isFunctionPointerType()) {
3775 QualType PointeeTy;
3776 if (const PointerType* PT = T->getAs<PointerType>()) {
3777 PointeeTy = PT->getPointeeType();
3778 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3779 T = convertFunctionTypeOfBlocks(FT);
3780 T = Context->getPointerType(T);
3781 }
3782 }
3783 }
3784
3785 convertToUnqualifiedObjCType(T);
3786 return T != oldT;
3787}
3788
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003789/// convertFunctionTypeOfBlocks - This routine converts a function type
3790/// whose result type may be a block pointer or whose argument type(s)
3791/// might be block pointers to an equivalent function type replacing
3792/// all block pointers to function pointers.
3793QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3794 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3795 // FTP will be null for closures that don't take arguments.
3796 // Generate a funky cast.
3797 SmallVector<QualType, 8> ArgTypes;
3798 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003799 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003800
3801 if (FTP) {
3802 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3803 E = FTP->arg_type_end(); I && (I != E); ++I) {
3804 QualType t = *I;
3805 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003806 if (convertObjCTypeToCStyleType(t))
3807 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003808 ArgTypes.push_back(t);
3809 }
3810 }
3811 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003812 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003813 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3814 else FuncType = QualType(FT, 0);
3815 return FuncType;
3816}
3817
3818Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3819 // Navigate to relevant type information.
3820 const BlockPointerType *CPT = 0;
3821
3822 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3823 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003824 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3825 CPT = MExpr->getType()->getAs<BlockPointerType>();
3826 }
3827 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3828 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3829 }
3830 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3831 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3832 else if (const ConditionalOperator *CEXPR =
3833 dyn_cast<ConditionalOperator>(BlockExp)) {
3834 Expr *LHSExp = CEXPR->getLHS();
3835 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3836 Expr *RHSExp = CEXPR->getRHS();
3837 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3838 Expr *CONDExp = CEXPR->getCond();
3839 ConditionalOperator *CondExpr =
3840 new (Context) ConditionalOperator(CONDExp,
3841 SourceLocation(), cast<Expr>(LHSStmt),
3842 SourceLocation(), cast<Expr>(RHSStmt),
3843 Exp->getType(), VK_RValue, OK_Ordinary);
3844 return CondExpr;
3845 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3846 CPT = IRE->getType()->getAs<BlockPointerType>();
3847 } else if (const PseudoObjectExpr *POE
3848 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3849 CPT = POE->getType()->castAs<BlockPointerType>();
3850 } else {
3851 assert(1 && "RewriteBlockClass: Bad type");
3852 }
3853 assert(CPT && "RewriteBlockClass: Bad type");
3854 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3855 assert(FT && "RewriteBlockClass: Bad type");
3856 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3857 // FTP will be null for closures that don't take arguments.
3858
3859 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3860 SourceLocation(), SourceLocation(),
3861 &Context->Idents.get("__block_impl"));
3862 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3863
3864 // Generate a funky cast.
3865 SmallVector<QualType, 8> ArgTypes;
3866
3867 // Push the block argument type.
3868 ArgTypes.push_back(PtrBlock);
3869 if (FTP) {
3870 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3871 E = FTP->arg_type_end(); I && (I != E); ++I) {
3872 QualType t = *I;
3873 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3874 if (!convertBlockPointerToFunctionPointer(t))
3875 convertToUnqualifiedObjCType(t);
3876 ArgTypes.push_back(t);
3877 }
3878 }
3879 // Now do the pointer to function cast.
3880 QualType PtrToFuncCastType
3881 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3882
3883 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3884
3885 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3886 CK_BitCast,
3887 const_cast<Expr*>(BlockExp));
3888 // Don't forget the parens to enforce the proper binding.
3889 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3890 BlkCast);
3891 //PE->dump();
3892
3893 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3894 SourceLocation(),
3895 &Context->Idents.get("FuncPtr"),
3896 Context->VoidPtrTy, 0,
3897 /*BitWidth=*/0, /*Mutable=*/true,
3898 /*HasInit=*/false);
3899 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3900 FD->getType(), VK_LValue,
3901 OK_Ordinary);
3902
3903
3904 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3905 CK_BitCast, ME);
3906 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3907
3908 SmallVector<Expr*, 8> BlkExprs;
3909 // Add the implicit argument.
3910 BlkExprs.push_back(BlkCast);
3911 // Add the user arguments.
3912 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3913 E = Exp->arg_end(); I != E; ++I) {
3914 BlkExprs.push_back(*I);
3915 }
3916 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3917 BlkExprs.size(),
3918 Exp->getType(), VK_RValue,
3919 SourceLocation());
3920 return CE;
3921}
3922
3923// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003924// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003925// For example:
3926//
3927// int main() {
3928// __block Foo *f;
3929// __block int i;
3930//
3931// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003932// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003933// i = 77;
3934// };
3935//}
John McCallf4b88a42012-03-10 09:33:50 +00003936Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003937 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3938 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003939 ValueDecl *VD = DeclRefExp->getDecl();
3940 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003941
3942 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3943 SourceLocation(),
3944 &Context->Idents.get("__forwarding"),
3945 Context->VoidPtrTy, 0,
3946 /*BitWidth=*/0, /*Mutable=*/true,
3947 /*HasInit=*/false);
3948 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3949 FD, SourceLocation(),
3950 FD->getType(), VK_LValue,
3951 OK_Ordinary);
3952
3953 StringRef Name = VD->getName();
3954 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3955 &Context->Idents.get(Name),
3956 Context->VoidPtrTy, 0,
3957 /*BitWidth=*/0, /*Mutable=*/true,
3958 /*HasInit=*/false);
3959 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3960 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3961
3962
3963
3964 // Need parens to enforce precedence.
3965 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3966 DeclRefExp->getExprLoc(),
3967 ME);
3968 ReplaceStmt(DeclRefExp, PE);
3969 return PE;
3970}
3971
3972// Rewrites the imported local variable V with external storage
3973// (static, extern, etc.) as *V
3974//
3975Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3976 ValueDecl *VD = DRE->getDecl();
3977 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3978 if (!ImportedLocalExternalDecls.count(Var))
3979 return DRE;
3980 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3981 VK_LValue, OK_Ordinary,
3982 DRE->getLocation());
3983 // Need parens to enforce precedence.
3984 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3985 Exp);
3986 ReplaceStmt(DRE, PE);
3987 return PE;
3988}
3989
3990void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3991 SourceLocation LocStart = CE->getLParenLoc();
3992 SourceLocation LocEnd = CE->getRParenLoc();
3993
3994 // Need to avoid trying to rewrite synthesized casts.
3995 if (LocStart.isInvalid())
3996 return;
3997 // Need to avoid trying to rewrite casts contained in macros.
3998 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3999 return;
4000
4001 const char *startBuf = SM->getCharacterData(LocStart);
4002 const char *endBuf = SM->getCharacterData(LocEnd);
4003 QualType QT = CE->getType();
4004 const Type* TypePtr = QT->getAs<Type>();
4005 if (isa<TypeOfExprType>(TypePtr)) {
4006 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4007 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4008 std::string TypeAsString = "(";
4009 RewriteBlockPointerType(TypeAsString, QT);
4010 TypeAsString += ")";
4011 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4012 return;
4013 }
4014 // advance the location to startArgList.
4015 const char *argPtr = startBuf;
4016
4017 while (*argPtr++ && (argPtr < endBuf)) {
4018 switch (*argPtr) {
4019 case '^':
4020 // Replace the '^' with '*'.
4021 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4022 ReplaceText(LocStart, 1, "*");
4023 break;
4024 }
4025 }
4026 return;
4027}
4028
4029void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4030 SourceLocation DeclLoc = FD->getLocation();
4031 unsigned parenCount = 0;
4032
4033 // We have 1 or more arguments that have closure pointers.
4034 const char *startBuf = SM->getCharacterData(DeclLoc);
4035 const char *startArgList = strchr(startBuf, '(');
4036
4037 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4038
4039 parenCount++;
4040 // advance the location to startArgList.
4041 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4042 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4043
4044 const char *argPtr = startArgList;
4045
4046 while (*argPtr++ && parenCount) {
4047 switch (*argPtr) {
4048 case '^':
4049 // Replace the '^' with '*'.
4050 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4051 ReplaceText(DeclLoc, 1, "*");
4052 break;
4053 case '(':
4054 parenCount++;
4055 break;
4056 case ')':
4057 parenCount--;
4058 break;
4059 }
4060 }
4061 return;
4062}
4063
4064bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4065 const FunctionProtoType *FTP;
4066 const PointerType *PT = QT->getAs<PointerType>();
4067 if (PT) {
4068 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4069 } else {
4070 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4071 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4072 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4073 }
4074 if (FTP) {
4075 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4076 E = FTP->arg_type_end(); I != E; ++I)
4077 if (isTopLevelBlockPointerType(*I))
4078 return true;
4079 }
4080 return false;
4081}
4082
4083bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4084 const FunctionProtoType *FTP;
4085 const PointerType *PT = QT->getAs<PointerType>();
4086 if (PT) {
4087 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4088 } else {
4089 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4090 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4091 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4092 }
4093 if (FTP) {
4094 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4095 E = FTP->arg_type_end(); I != E; ++I) {
4096 if ((*I)->isObjCQualifiedIdType())
4097 return true;
4098 if ((*I)->isObjCObjectPointerType() &&
4099 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4100 return true;
4101 }
4102
4103 }
4104 return false;
4105}
4106
4107void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4108 const char *&RParen) {
4109 const char *argPtr = strchr(Name, '(');
4110 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4111
4112 LParen = argPtr; // output the start.
4113 argPtr++; // skip past the left paren.
4114 unsigned parenCount = 1;
4115
4116 while (*argPtr && parenCount) {
4117 switch (*argPtr) {
4118 case '(': parenCount++; break;
4119 case ')': parenCount--; break;
4120 default: break;
4121 }
4122 if (parenCount) argPtr++;
4123 }
4124 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4125 RParen = argPtr; // output the end
4126}
4127
4128void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4129 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4130 RewriteBlockPointerFunctionArgs(FD);
4131 return;
4132 }
4133 // Handle Variables and Typedefs.
4134 SourceLocation DeclLoc = ND->getLocation();
4135 QualType DeclT;
4136 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4137 DeclT = VD->getType();
4138 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4139 DeclT = TDD->getUnderlyingType();
4140 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4141 DeclT = FD->getType();
4142 else
4143 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4144
4145 const char *startBuf = SM->getCharacterData(DeclLoc);
4146 const char *endBuf = startBuf;
4147 // scan backward (from the decl location) for the end of the previous decl.
4148 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4149 startBuf--;
4150 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4151 std::string buf;
4152 unsigned OrigLength=0;
4153 // *startBuf != '^' if we are dealing with a pointer to function that
4154 // may take block argument types (which will be handled below).
4155 if (*startBuf == '^') {
4156 // Replace the '^' with '*', computing a negative offset.
4157 buf = '*';
4158 startBuf++;
4159 OrigLength++;
4160 }
4161 while (*startBuf != ')') {
4162 buf += *startBuf;
4163 startBuf++;
4164 OrigLength++;
4165 }
4166 buf += ')';
4167 OrigLength++;
4168
4169 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4170 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4171 // Replace the '^' with '*' for arguments.
4172 // Replace id<P> with id/*<>*/
4173 DeclLoc = ND->getLocation();
4174 startBuf = SM->getCharacterData(DeclLoc);
4175 const char *argListBegin, *argListEnd;
4176 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4177 while (argListBegin < argListEnd) {
4178 if (*argListBegin == '^')
4179 buf += '*';
4180 else if (*argListBegin == '<') {
4181 buf += "/*";
4182 buf += *argListBegin++;
4183 OrigLength++;;
4184 while (*argListBegin != '>') {
4185 buf += *argListBegin++;
4186 OrigLength++;
4187 }
4188 buf += *argListBegin;
4189 buf += "*/";
4190 }
4191 else
4192 buf += *argListBegin;
4193 argListBegin++;
4194 OrigLength++;
4195 }
4196 buf += ')';
4197 OrigLength++;
4198 }
4199 ReplaceText(Start, OrigLength, buf);
4200
4201 return;
4202}
4203
4204
4205/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4206/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4207/// struct Block_byref_id_object *src) {
4208/// _Block_object_assign (&_dest->object, _src->object,
4209/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4210/// [|BLOCK_FIELD_IS_WEAK]) // object
4211/// _Block_object_assign(&_dest->object, _src->object,
4212/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4213/// [|BLOCK_FIELD_IS_WEAK]) // block
4214/// }
4215/// And:
4216/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4217/// _Block_object_dispose(_src->object,
4218/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4219/// [|BLOCK_FIELD_IS_WEAK]) // object
4220/// _Block_object_dispose(_src->object,
4221/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4222/// [|BLOCK_FIELD_IS_WEAK]) // block
4223/// }
4224
4225std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4226 int flag) {
4227 std::string S;
4228 if (CopyDestroyCache.count(flag))
4229 return S;
4230 CopyDestroyCache.insert(flag);
4231 S = "static void __Block_byref_id_object_copy_";
4232 S += utostr(flag);
4233 S += "(void *dst, void *src) {\n";
4234
4235 // offset into the object pointer is computed as:
4236 // void * + void* + int + int + void* + void *
4237 unsigned IntSize =
4238 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4239 unsigned VoidPtrSize =
4240 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4241
4242 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4243 S += " _Block_object_assign((char*)dst + ";
4244 S += utostr(offset);
4245 S += ", *(void * *) ((char*)src + ";
4246 S += utostr(offset);
4247 S += "), ";
4248 S += utostr(flag);
4249 S += ");\n}\n";
4250
4251 S += "static void __Block_byref_id_object_dispose_";
4252 S += utostr(flag);
4253 S += "(void *src) {\n";
4254 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4255 S += utostr(offset);
4256 S += "), ";
4257 S += utostr(flag);
4258 S += ");\n}\n";
4259 return S;
4260}
4261
4262/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4263/// the declaration into:
4264/// struct __Block_byref_ND {
4265/// void *__isa; // NULL for everything except __weak pointers
4266/// struct __Block_byref_ND *__forwarding;
4267/// int32_t __flags;
4268/// int32_t __size;
4269/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4270/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4271/// typex ND;
4272/// };
4273///
4274/// It then replaces declaration of ND variable with:
4275/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4276/// __size=sizeof(struct __Block_byref_ND),
4277/// ND=initializer-if-any};
4278///
4279///
4280void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4281 // Insert declaration for the function in which block literal is
4282 // used.
4283 if (CurFunctionDeclToDeclareForBlock)
4284 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4285 int flag = 0;
4286 int isa = 0;
4287 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4288 if (DeclLoc.isInvalid())
4289 // If type location is missing, it is because of missing type (a warning).
4290 // Use variable's location which is good for this case.
4291 DeclLoc = ND->getLocation();
4292 const char *startBuf = SM->getCharacterData(DeclLoc);
4293 SourceLocation X = ND->getLocEnd();
4294 X = SM->getExpansionLoc(X);
4295 const char *endBuf = SM->getCharacterData(X);
4296 std::string Name(ND->getNameAsString());
4297 std::string ByrefType;
4298 RewriteByRefString(ByrefType, Name, ND, true);
4299 ByrefType += " {\n";
4300 ByrefType += " void *__isa;\n";
4301 RewriteByRefString(ByrefType, Name, ND);
4302 ByrefType += " *__forwarding;\n";
4303 ByrefType += " int __flags;\n";
4304 ByrefType += " int __size;\n";
4305 // Add void *__Block_byref_id_object_copy;
4306 // void *__Block_byref_id_object_dispose; if needed.
4307 QualType Ty = ND->getType();
4308 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4309 if (HasCopyAndDispose) {
4310 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4311 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4312 }
4313
4314 QualType T = Ty;
4315 (void)convertBlockPointerToFunctionPointer(T);
4316 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4317
4318 ByrefType += " " + Name + ";\n";
4319 ByrefType += "};\n";
4320 // Insert this type in global scope. It is needed by helper function.
4321 SourceLocation FunLocStart;
4322 if (CurFunctionDef)
4323 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4324 else {
4325 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4326 FunLocStart = CurMethodDef->getLocStart();
4327 }
4328 InsertText(FunLocStart, ByrefType);
4329 if (Ty.isObjCGCWeak()) {
4330 flag |= BLOCK_FIELD_IS_WEAK;
4331 isa = 1;
4332 }
4333
4334 if (HasCopyAndDispose) {
4335 flag = BLOCK_BYREF_CALLER;
4336 QualType Ty = ND->getType();
4337 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4338 if (Ty->isBlockPointerType())
4339 flag |= BLOCK_FIELD_IS_BLOCK;
4340 else
4341 flag |= BLOCK_FIELD_IS_OBJECT;
4342 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4343 if (!HF.empty())
4344 InsertText(FunLocStart, HF);
4345 }
4346
4347 // struct __Block_byref_ND ND =
4348 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4349 // initializer-if-any};
4350 bool hasInit = (ND->getInit() != 0);
4351 unsigned flags = 0;
4352 if (HasCopyAndDispose)
4353 flags |= BLOCK_HAS_COPY_DISPOSE;
4354 Name = ND->getNameAsString();
4355 ByrefType.clear();
4356 RewriteByRefString(ByrefType, Name, ND);
4357 std::string ForwardingCastType("(");
4358 ForwardingCastType += ByrefType + " *)";
4359 if (!hasInit) {
4360 ByrefType += " " + Name + " = {(void*)";
4361 ByrefType += utostr(isa);
4362 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4363 ByrefType += utostr(flags);
4364 ByrefType += ", ";
4365 ByrefType += "sizeof(";
4366 RewriteByRefString(ByrefType, Name, ND);
4367 ByrefType += ")";
4368 if (HasCopyAndDispose) {
4369 ByrefType += ", __Block_byref_id_object_copy_";
4370 ByrefType += utostr(flag);
4371 ByrefType += ", __Block_byref_id_object_dispose_";
4372 ByrefType += utostr(flag);
4373 }
4374 ByrefType += "};\n";
4375 unsigned nameSize = Name.size();
4376 // for block or function pointer declaration. Name is aleady
4377 // part of the declaration.
4378 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4379 nameSize = 1;
4380 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4381 }
4382 else {
4383 SourceLocation startLoc;
4384 Expr *E = ND->getInit();
4385 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4386 startLoc = ECE->getLParenLoc();
4387 else
4388 startLoc = E->getLocStart();
4389 startLoc = SM->getExpansionLoc(startLoc);
4390 endBuf = SM->getCharacterData(startLoc);
4391 ByrefType += " " + Name;
4392 ByrefType += " = {(void*)";
4393 ByrefType += utostr(isa);
4394 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4395 ByrefType += utostr(flags);
4396 ByrefType += ", ";
4397 ByrefType += "sizeof(";
4398 RewriteByRefString(ByrefType, Name, ND);
4399 ByrefType += "), ";
4400 if (HasCopyAndDispose) {
4401 ByrefType += "__Block_byref_id_object_copy_";
4402 ByrefType += utostr(flag);
4403 ByrefType += ", __Block_byref_id_object_dispose_";
4404 ByrefType += utostr(flag);
4405 ByrefType += ", ";
4406 }
4407 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4408
4409 // Complete the newly synthesized compound expression by inserting a right
4410 // curly brace before the end of the declaration.
4411 // FIXME: This approach avoids rewriting the initializer expression. It
4412 // also assumes there is only one declarator. For example, the following
4413 // isn't currently supported by this routine (in general):
4414 //
4415 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4416 //
4417 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4418 const char *semiBuf = strchr(startInitializerBuf, ';');
4419 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4420 SourceLocation semiLoc =
4421 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4422
4423 InsertText(semiLoc, "}");
4424 }
4425 return;
4426}
4427
4428void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4429 // Add initializers for any closure decl refs.
4430 GetBlockDeclRefExprs(Exp->getBody());
4431 if (BlockDeclRefs.size()) {
4432 // Unique all "by copy" declarations.
4433 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004434 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004435 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4436 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4437 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4438 }
4439 }
4440 // Unique all "by ref" declarations.
4441 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004442 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004443 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4444 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4445 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4446 }
4447 }
4448 // Find any imported blocks...they will need special attention.
4449 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004450 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004451 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4452 BlockDeclRefs[i]->getType()->isBlockPointerType())
4453 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4454 }
4455}
4456
4457FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4458 IdentifierInfo *ID = &Context->Idents.get(name);
4459 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4460 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4461 SourceLocation(), ID, FType, 0, SC_Extern,
4462 SC_None, false, false);
4463}
4464
4465Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004466 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004467 const BlockDecl *block = Exp->getBlockDecl();
4468 Blocks.push_back(Exp);
4469
4470 CollectBlockDeclRefInfo(Exp);
4471
4472 // Add inner imported variables now used in current block.
4473 int countOfInnerDecls = 0;
4474 if (!InnerBlockDeclRefs.empty()) {
4475 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004476 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004477 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004478 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004479 // We need to save the copied-in variables in nested
4480 // blocks because it is needed at the end for some of the API generations.
4481 // See SynthesizeBlockLiterals routine.
4482 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4483 BlockDeclRefs.push_back(Exp);
4484 BlockByCopyDeclsPtrSet.insert(VD);
4485 BlockByCopyDecls.push_back(VD);
4486 }
John McCallf4b88a42012-03-10 09:33:50 +00004487 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004488 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4489 BlockDeclRefs.push_back(Exp);
4490 BlockByRefDeclsPtrSet.insert(VD);
4491 BlockByRefDecls.push_back(VD);
4492 }
4493 }
4494 // Find any imported blocks...they will need special attention.
4495 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004496 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004497 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4498 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4499 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4500 }
4501 InnerDeclRefsCount.push_back(countOfInnerDecls);
4502
4503 std::string FuncName;
4504
4505 if (CurFunctionDef)
4506 FuncName = CurFunctionDef->getNameAsString();
4507 else if (CurMethodDef)
4508 BuildUniqueMethodName(FuncName, CurMethodDef);
4509 else if (GlobalVarDecl)
4510 FuncName = std::string(GlobalVarDecl->getNameAsString());
4511
4512 std::string BlockNumber = utostr(Blocks.size()-1);
4513
4514 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4515 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4516
4517 // Get a pointer to the function type so we can cast appropriately.
4518 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4519 QualType FType = Context->getPointerType(BFT);
4520
4521 FunctionDecl *FD;
4522 Expr *NewRep;
4523
4524 // Simulate a contructor call...
4525 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004526 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004527 SourceLocation());
4528
4529 SmallVector<Expr*, 4> InitExprs;
4530
4531 // Initialize the block function.
4532 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004533 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4534 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004535 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4536 CK_BitCast, Arg);
4537 InitExprs.push_back(castExpr);
4538
4539 // Initialize the block descriptor.
4540 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4541
4542 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4543 SourceLocation(), SourceLocation(),
4544 &Context->Idents.get(DescData.c_str()),
4545 Context->VoidPtrTy, 0,
4546 SC_Static, SC_None);
4547 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004548 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004549 Context->VoidPtrTy,
4550 VK_LValue,
4551 SourceLocation()),
4552 UO_AddrOf,
4553 Context->getPointerType(Context->VoidPtrTy),
4554 VK_RValue, OK_Ordinary,
4555 SourceLocation());
4556 InitExprs.push_back(DescRefExpr);
4557
4558 // Add initializers for any closure decl refs.
4559 if (BlockDeclRefs.size()) {
4560 Expr *Exp;
4561 // Output all "by copy" declarations.
4562 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4563 E = BlockByCopyDecls.end(); I != E; ++I) {
4564 if (isObjCType((*I)->getType())) {
4565 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4566 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004567 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4568 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004569 if (HasLocalVariableExternalStorage(*I)) {
4570 QualType QT = (*I)->getType();
4571 QT = Context->getPointerType(QT);
4572 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4573 OK_Ordinary, SourceLocation());
4574 }
4575 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4576 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004577 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4578 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004579 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4580 CK_BitCast, Arg);
4581 } else {
4582 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004583 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4584 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004585 if (HasLocalVariableExternalStorage(*I)) {
4586 QualType QT = (*I)->getType();
4587 QT = Context->getPointerType(QT);
4588 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4589 OK_Ordinary, SourceLocation());
4590 }
4591
4592 }
4593 InitExprs.push_back(Exp);
4594 }
4595 // Output all "by ref" declarations.
4596 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4597 E = BlockByRefDecls.end(); I != E; ++I) {
4598 ValueDecl *ND = (*I);
4599 std::string Name(ND->getNameAsString());
4600 std::string RecName;
4601 RewriteByRefString(RecName, Name, ND, true);
4602 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4603 + sizeof("struct"));
4604 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4605 SourceLocation(), SourceLocation(),
4606 II);
4607 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4608 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4609
4610 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004611 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004612 SourceLocation());
4613 bool isNestedCapturedVar = false;
4614 if (block)
4615 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4616 ce = block->capture_end(); ci != ce; ++ci) {
4617 const VarDecl *variable = ci->getVariable();
4618 if (variable == ND && ci->isNested()) {
4619 assert (ci->isByRef() &&
4620 "SynthBlockInitExpr - captured block variable is not byref");
4621 isNestedCapturedVar = true;
4622 break;
4623 }
4624 }
4625 // captured nested byref variable has its address passed. Do not take
4626 // its address again.
4627 if (!isNestedCapturedVar)
4628 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4629 Context->getPointerType(Exp->getType()),
4630 VK_RValue, OK_Ordinary, SourceLocation());
4631 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4632 InitExprs.push_back(Exp);
4633 }
4634 }
4635 if (ImportedBlockDecls.size()) {
4636 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4637 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4638 unsigned IntSize =
4639 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4640 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4641 Context->IntTy, SourceLocation());
4642 InitExprs.push_back(FlagExp);
4643 }
4644 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4645 FType, VK_LValue, SourceLocation());
4646 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4647 Context->getPointerType(NewRep->getType()),
4648 VK_RValue, OK_Ordinary, SourceLocation());
4649 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4650 NewRep);
4651 BlockDeclRefs.clear();
4652 BlockByRefDecls.clear();
4653 BlockByRefDeclsPtrSet.clear();
4654 BlockByCopyDecls.clear();
4655 BlockByCopyDeclsPtrSet.clear();
4656 ImportedBlockDecls.clear();
4657 return NewRep;
4658}
4659
4660bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4661 if (const ObjCForCollectionStmt * CS =
4662 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4663 return CS->getElement() == DS;
4664 return false;
4665}
4666
4667//===----------------------------------------------------------------------===//
4668// Function Body / Expression rewriting
4669//===----------------------------------------------------------------------===//
4670
4671Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4672 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4673 isa<DoStmt>(S) || isa<ForStmt>(S))
4674 Stmts.push_back(S);
4675 else if (isa<ObjCForCollectionStmt>(S)) {
4676 Stmts.push_back(S);
4677 ObjCBcLabelNo.push_back(++BcLabelCount);
4678 }
4679
4680 // Pseudo-object operations and ivar references need special
4681 // treatment because we're going to recursively rewrite them.
4682 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4683 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4684 return RewritePropertyOrImplicitSetter(PseudoOp);
4685 } else {
4686 return RewritePropertyOrImplicitGetter(PseudoOp);
4687 }
4688 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4689 return RewriteObjCIvarRefExpr(IvarRefExpr);
4690 }
4691
4692 SourceRange OrigStmtRange = S->getSourceRange();
4693
4694 // Perform a bottom up rewrite of all children.
4695 for (Stmt::child_range CI = S->children(); CI; ++CI)
4696 if (*CI) {
4697 Stmt *childStmt = (*CI);
4698 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4699 if (newStmt) {
4700 *CI = newStmt;
4701 }
4702 }
4703
4704 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004705 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004706 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4707 InnerContexts.insert(BE->getBlockDecl());
4708 ImportedLocalExternalDecls.clear();
4709 GetInnerBlockDeclRefExprs(BE->getBody(),
4710 InnerBlockDeclRefs, InnerContexts);
4711 // Rewrite the block body in place.
4712 Stmt *SaveCurrentBody = CurrentBody;
4713 CurrentBody = BE->getBody();
4714 PropParentMap = 0;
4715 // block literal on rhs of a property-dot-sytax assignment
4716 // must be replaced by its synthesize ast so getRewrittenText
4717 // works as expected. In this case, what actually ends up on RHS
4718 // is the blockTranscribed which is the helper function for the
4719 // block literal; as in: self.c = ^() {[ace ARR];};
4720 bool saveDisableReplaceStmt = DisableReplaceStmt;
4721 DisableReplaceStmt = false;
4722 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4723 DisableReplaceStmt = saveDisableReplaceStmt;
4724 CurrentBody = SaveCurrentBody;
4725 PropParentMap = 0;
4726 ImportedLocalExternalDecls.clear();
4727 // Now we snarf the rewritten text and stash it away for later use.
4728 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4729 RewrittenBlockExprs[BE] = Str;
4730
4731 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4732
4733 //blockTranscribed->dump();
4734 ReplaceStmt(S, blockTranscribed);
4735 return blockTranscribed;
4736 }
4737 // Handle specific things.
4738 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4739 return RewriteAtEncode(AtEncode);
4740
4741 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4742 return RewriteAtSelector(AtSelector);
4743
4744 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4745 return RewriteObjCStringLiteral(AtString);
4746
4747 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4748#if 0
4749 // Before we rewrite it, put the original message expression in a comment.
4750 SourceLocation startLoc = MessExpr->getLocStart();
4751 SourceLocation endLoc = MessExpr->getLocEnd();
4752
4753 const char *startBuf = SM->getCharacterData(startLoc);
4754 const char *endBuf = SM->getCharacterData(endLoc);
4755
4756 std::string messString;
4757 messString += "// ";
4758 messString.append(startBuf, endBuf-startBuf+1);
4759 messString += "\n";
4760
4761 // FIXME: Missing definition of
4762 // InsertText(clang::SourceLocation, char const*, unsigned int).
4763 // InsertText(startLoc, messString.c_str(), messString.size());
4764 // Tried this, but it didn't work either...
4765 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4766#endif
4767 return RewriteMessageExpr(MessExpr);
4768 }
4769
4770 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4771 return RewriteObjCTryStmt(StmtTry);
4772
4773 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4774 return RewriteObjCSynchronizedStmt(StmtTry);
4775
4776 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4777 return RewriteObjCThrowStmt(StmtThrow);
4778
4779 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4780 return RewriteObjCProtocolExpr(ProtocolExp);
4781
4782 if (ObjCForCollectionStmt *StmtForCollection =
4783 dyn_cast<ObjCForCollectionStmt>(S))
4784 return RewriteObjCForCollectionStmt(StmtForCollection,
4785 OrigStmtRange.getEnd());
4786 if (BreakStmt *StmtBreakStmt =
4787 dyn_cast<BreakStmt>(S))
4788 return RewriteBreakStmt(StmtBreakStmt);
4789 if (ContinueStmt *StmtContinueStmt =
4790 dyn_cast<ContinueStmt>(S))
4791 return RewriteContinueStmt(StmtContinueStmt);
4792
4793 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4794 // and cast exprs.
4795 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4796 // FIXME: What we're doing here is modifying the type-specifier that
4797 // precedes the first Decl. In the future the DeclGroup should have
4798 // a separate type-specifier that we can rewrite.
4799 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4800 // the context of an ObjCForCollectionStmt. For example:
4801 // NSArray *someArray;
4802 // for (id <FooProtocol> index in someArray) ;
4803 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4804 // and it depends on the original text locations/positions.
4805 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4806 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4807
4808 // Blocks rewrite rules.
4809 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4810 DI != DE; ++DI) {
4811 Decl *SD = *DI;
4812 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4813 if (isTopLevelBlockPointerType(ND->getType()))
4814 RewriteBlockPointerDecl(ND);
4815 else if (ND->getType()->isFunctionPointerType())
4816 CheckFunctionPointerDecl(ND->getType(), ND);
4817 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4818 if (VD->hasAttr<BlocksAttr>()) {
4819 static unsigned uniqueByrefDeclCount = 0;
4820 assert(!BlockByRefDeclNo.count(ND) &&
4821 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4822 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4823 RewriteByRefVar(VD);
4824 }
4825 else
4826 RewriteTypeOfDecl(VD);
4827 }
4828 }
4829 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4830 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4831 RewriteBlockPointerDecl(TD);
4832 else if (TD->getUnderlyingType()->isFunctionPointerType())
4833 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4834 }
4835 }
4836 }
4837
4838 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4839 RewriteObjCQualifiedInterfaceTypes(CE);
4840
4841 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4842 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4843 assert(!Stmts.empty() && "Statement stack is empty");
4844 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4845 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4846 && "Statement stack mismatch");
4847 Stmts.pop_back();
4848 }
4849 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4851 ValueDecl *VD = DRE->getDecl();
4852 if (VD->hasAttr<BlocksAttr>())
4853 return RewriteBlockDeclRefExpr(DRE);
4854 if (HasLocalVariableExternalStorage(VD))
4855 return RewriteLocalVariableExternalStorage(DRE);
4856 }
4857
4858 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4859 if (CE->getCallee()->getType()->isBlockPointerType()) {
4860 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4861 ReplaceStmt(S, BlockCall);
4862 return BlockCall;
4863 }
4864 }
4865 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4866 RewriteCastExpr(CE);
4867 }
4868#if 0
4869 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4870 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4871 ICE->getSubExpr(),
4872 SourceLocation());
4873 // Get the new text.
4874 std::string SStr;
4875 llvm::raw_string_ostream Buf(SStr);
4876 Replacement->printPretty(Buf, *Context);
4877 const std::string &Str = Buf.str();
4878
4879 printf("CAST = %s\n", &Str[0]);
4880 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4881 delete S;
4882 return Replacement;
4883 }
4884#endif
4885 // Return this stmt unmodified.
4886 return S;
4887}
4888
4889void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4890 for (RecordDecl::field_iterator i = RD->field_begin(),
4891 e = RD->field_end(); i != e; ++i) {
4892 FieldDecl *FD = *i;
4893 if (isTopLevelBlockPointerType(FD->getType()))
4894 RewriteBlockPointerDecl(FD);
4895 if (FD->getType()->isObjCQualifiedIdType() ||
4896 FD->getType()->isObjCQualifiedInterfaceType())
4897 RewriteObjCQualifiedInterfaceTypes(FD);
4898 }
4899}
4900
4901/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4902/// main file of the input.
4903void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4904 switch (D->getKind()) {
4905 case Decl::Function: {
4906 FunctionDecl *FD = cast<FunctionDecl>(D);
4907 if (FD->isOverloadedOperator())
4908 return;
4909
4910 // Since function prototypes don't have ParmDecl's, we check the function
4911 // prototype. This enables us to rewrite function declarations and
4912 // definitions using the same code.
4913 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4914
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004915 if (!FD->isThisDeclarationADefinition())
4916 break;
4917
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004918 // FIXME: If this should support Obj-C++, support CXXTryStmt
4919 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4920 CurFunctionDef = FD;
4921 CurFunctionDeclToDeclareForBlock = FD;
4922 CurrentBody = Body;
4923 Body =
4924 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4925 FD->setBody(Body);
4926 CurrentBody = 0;
4927 if (PropParentMap) {
4928 delete PropParentMap;
4929 PropParentMap = 0;
4930 }
4931 // This synthesizes and inserts the block "impl" struct, invoke function,
4932 // and any copy/dispose helper functions.
4933 InsertBlockLiteralsWithinFunction(FD);
4934 CurFunctionDef = 0;
4935 CurFunctionDeclToDeclareForBlock = 0;
4936 }
4937 break;
4938 }
4939 case Decl::ObjCMethod: {
4940 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4941 if (CompoundStmt *Body = MD->getCompoundBody()) {
4942 CurMethodDef = MD;
4943 CurrentBody = Body;
4944 Body =
4945 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4946 MD->setBody(Body);
4947 CurrentBody = 0;
4948 if (PropParentMap) {
4949 delete PropParentMap;
4950 PropParentMap = 0;
4951 }
4952 InsertBlockLiteralsWithinMethod(MD);
4953 CurMethodDef = 0;
4954 }
4955 break;
4956 }
4957 case Decl::ObjCImplementation: {
4958 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4959 ClassImplementation.push_back(CI);
4960 break;
4961 }
4962 case Decl::ObjCCategoryImpl: {
4963 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4964 CategoryImplementation.push_back(CI);
4965 break;
4966 }
4967 case Decl::Var: {
4968 VarDecl *VD = cast<VarDecl>(D);
4969 RewriteObjCQualifiedInterfaceTypes(VD);
4970 if (isTopLevelBlockPointerType(VD->getType()))
4971 RewriteBlockPointerDecl(VD);
4972 else if (VD->getType()->isFunctionPointerType()) {
4973 CheckFunctionPointerDecl(VD->getType(), VD);
4974 if (VD->getInit()) {
4975 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4976 RewriteCastExpr(CE);
4977 }
4978 }
4979 } else if (VD->getType()->isRecordType()) {
4980 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4981 if (RD->isCompleteDefinition())
4982 RewriteRecordBody(RD);
4983 }
4984 if (VD->getInit()) {
4985 GlobalVarDecl = VD;
4986 CurrentBody = VD->getInit();
4987 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4988 CurrentBody = 0;
4989 if (PropParentMap) {
4990 delete PropParentMap;
4991 PropParentMap = 0;
4992 }
4993 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4994 GlobalVarDecl = 0;
4995
4996 // This is needed for blocks.
4997 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4998 RewriteCastExpr(CE);
4999 }
5000 }
5001 break;
5002 }
5003 case Decl::TypeAlias:
5004 case Decl::Typedef: {
5005 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5006 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5007 RewriteBlockPointerDecl(TD);
5008 else if (TD->getUnderlyingType()->isFunctionPointerType())
5009 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5010 }
5011 break;
5012 }
5013 case Decl::CXXRecord:
5014 case Decl::Record: {
5015 RecordDecl *RD = cast<RecordDecl>(D);
5016 if (RD->isCompleteDefinition())
5017 RewriteRecordBody(RD);
5018 break;
5019 }
5020 default:
5021 break;
5022 }
5023 // Nothing yet.
5024}
5025
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005026/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5027/// protocol reference symbols in the for of:
5028/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5029static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5030 ObjCProtocolDecl *PDecl,
5031 std::string &Result) {
5032 // Also output .objc_protorefs$B section and its meta-data.
5033 if (Context->getLangOpts().MicrosoftExt)
5034 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5035 Result += "struct _protocol_t *";
5036 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5037 Result += PDecl->getNameAsString();
5038 Result += " = &";
5039 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5040 Result += ";\n";
5041}
5042
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005043void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5044 if (Diags.hasErrorOccurred())
5045 return;
5046
5047 RewriteInclude();
5048
5049 // Here's a great place to add any extra declarations that may be needed.
5050 // Write out meta data for each @protocol(<expr>).
5051 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005052 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005053 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005054 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5055 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005056
5057 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005058 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5059 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5060 // Write struct declaration for the class matching its ivar declarations.
5061 // Note that for modern abi, this is postponed until the end of TU
5062 // because class extensions and the implementation might declare their own
5063 // private ivars.
5064 RewriteInterfaceDecl(CDecl);
5065 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005066
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005067 if (ClassImplementation.size() || CategoryImplementation.size())
5068 RewriteImplementations();
5069
5070 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5071 // we are done.
5072 if (const RewriteBuffer *RewriteBuf =
5073 Rewrite.getRewriteBufferFor(MainFileID)) {
5074 //printf("Changed:\n");
5075 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5076 } else {
5077 llvm::errs() << "No changes\n";
5078 }
5079
5080 if (ClassImplementation.size() || CategoryImplementation.size() ||
5081 ProtocolExprDecls.size()) {
5082 // Rewrite Objective-c meta data*
5083 std::string ResultStr;
5084 RewriteMetaDataIntoBuffer(ResultStr);
5085 // Emit metadata.
5086 *OutFile << ResultStr;
5087 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005088 // Emit ImageInfo;
5089 {
5090 std::string ResultStr;
5091 WriteImageInfo(ResultStr);
5092 *OutFile << ResultStr;
5093 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005094 OutFile->flush();
5095}
5096
5097void RewriteModernObjC::Initialize(ASTContext &context) {
5098 InitializeCommon(context);
5099
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005100 Preamble += "#ifndef __OBJC2__\n";
5101 Preamble += "#define __OBJC2__\n";
5102 Preamble += "#endif\n";
5103
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005104 // declaring objc_selector outside the parameter list removes a silly
5105 // scope related warning...
5106 if (IsHeader)
5107 Preamble = "#pragma once\n";
5108 Preamble += "struct objc_selector; struct objc_class;\n";
5109 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5110 Preamble += "struct objc_object *superClass; ";
5111 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005112 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005113 // These are currently generated.
5114 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005115 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005116 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5117 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005118 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5119 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005120 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005121 // These are generated but not necessary for functionality.
5122 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5123 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005124 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5125 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005126 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005127
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005128 // These need be generated for performance. Currently they are not,
5129 // using API calls instead.
5130 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5131 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5132 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5133
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005134 // Add a constructor for creating temporary objects.
5135 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5136 ": ";
5137 Preamble += "object(o), superClass(s) {} ";
5138 }
5139 Preamble += "};\n";
5140 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5141 Preamble += "typedef struct objc_object Protocol;\n";
5142 Preamble += "#define _REWRITER_typedef_Protocol\n";
5143 Preamble += "#endif\n";
5144 if (LangOpts.MicrosoftExt) {
5145 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5146 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5147 } else
5148 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5149 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5150 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5151 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5152 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5153 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5154 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5155 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5156 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5157 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5158 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5159 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5160 Preamble += "(const char *);\n";
5161 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5162 Preamble += "(struct objc_class *);\n";
5163 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5164 Preamble += "(const char *);\n";
Fariborz Jahanianb1228182012-03-15 22:42:15 +00005165 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5167 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5168 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5170 Preamble += "(struct objc_class *, struct objc_object *);\n";
5171 // @synchronized hooks.
Fariborz Jahanian542125f2012-03-16 21:33:16 +00005172 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(id);\n";
5173 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005174 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5175 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5176 Preamble += "struct __objcFastEnumerationState {\n\t";
5177 Preamble += "unsigned long state;\n\t";
5178 Preamble += "void **itemsPtr;\n\t";
5179 Preamble += "unsigned long *mutationsPtr;\n\t";
5180 Preamble += "unsigned long extra[5];\n};\n";
5181 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5182 Preamble += "#define __FASTENUMERATIONSTATE\n";
5183 Preamble += "#endif\n";
5184 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5185 Preamble += "struct __NSConstantStringImpl {\n";
5186 Preamble += " int *isa;\n";
5187 Preamble += " int flags;\n";
5188 Preamble += " char *str;\n";
5189 Preamble += " long length;\n";
5190 Preamble += "};\n";
5191 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5192 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5193 Preamble += "#else\n";
5194 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5195 Preamble += "#endif\n";
5196 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5197 Preamble += "#endif\n";
5198 // Blocks preamble.
5199 Preamble += "#ifndef BLOCK_IMPL\n";
5200 Preamble += "#define BLOCK_IMPL\n";
5201 Preamble += "struct __block_impl {\n";
5202 Preamble += " void *isa;\n";
5203 Preamble += " int Flags;\n";
5204 Preamble += " int Reserved;\n";
5205 Preamble += " void *FuncPtr;\n";
5206 Preamble += "};\n";
5207 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5208 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5209 Preamble += "extern \"C\" __declspec(dllexport) "
5210 "void _Block_object_assign(void *, const void *, const int);\n";
5211 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5212 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5213 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5214 Preamble += "#else\n";
5215 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5216 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5217 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5218 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5219 Preamble += "#endif\n";
5220 Preamble += "#endif\n";
5221 if (LangOpts.MicrosoftExt) {
5222 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5223 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5224 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5225 Preamble += "#define __attribute__(X)\n";
5226 Preamble += "#endif\n";
5227 Preamble += "#define __weak\n";
5228 }
5229 else {
5230 Preamble += "#define __block\n";
5231 Preamble += "#define __weak\n";
5232 }
5233 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5234 // as this avoids warning in any 64bit/32bit compilation model.
5235 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5236}
5237
5238/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5239/// ivar offset.
5240void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5241 std::string &Result) {
5242 if (ivar->isBitField()) {
5243 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5244 // place all bitfields at offset 0.
5245 Result += "0";
5246 } else {
5247 Result += "__OFFSETOFIVAR__(struct ";
5248 Result += ivar->getContainingInterface()->getNameAsString();
5249 if (LangOpts.MicrosoftExt)
5250 Result += "_IMPL";
5251 Result += ", ";
5252 Result += ivar->getNameAsString();
5253 Result += ")";
5254 }
5255}
5256
5257/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5258/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005259/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005260/// char *attributes;
5261/// }
5262
5263/// struct _prop_list_t {
5264/// uint32_t entsize; // sizeof(struct _prop_t)
5265/// uint32_t count_of_properties;
5266/// struct _prop_t prop_list[count_of_properties];
5267/// }
5268
5269/// struct _protocol_t;
5270
5271/// struct _protocol_list_t {
5272/// long protocol_count; // Note, this is 32/64 bit
5273/// struct _protocol_t * protocol_list[protocol_count];
5274/// }
5275
5276/// struct _objc_method {
5277/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005278/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005279/// char *_imp;
5280/// }
5281
5282/// struct _method_list_t {
5283/// uint32_t entsize; // sizeof(struct _objc_method)
5284/// uint32_t method_count;
5285/// struct _objc_method method_list[method_count];
5286/// }
5287
5288/// struct _protocol_t {
5289/// id isa; // NULL
5290/// const char * const protocol_name;
5291/// const struct _protocol_list_t * protocol_list; // super protocols
5292/// const struct method_list_t * const instance_methods;
5293/// const struct method_list_t * const class_methods;
5294/// const struct method_list_t *optionalInstanceMethods;
5295/// const struct method_list_t *optionalClassMethods;
5296/// const struct _prop_list_t * properties;
5297/// const uint32_t size; // sizeof(struct _protocol_t)
5298/// const uint32_t flags; // = 0
5299/// const char ** extendedMethodTypes;
5300/// }
5301
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005302/// struct _ivar_t {
5303/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005304/// const char *name;
5305/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005306/// uint32_t alignment;
5307/// uint32_t size;
5308/// }
5309
5310/// struct _ivar_list_t {
5311/// uint32 entsize; // sizeof(struct _ivar_t)
5312/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005313/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005314/// }
5315
5316/// struct _class_ro_t {
5317/// uint32_t const flags;
5318/// uint32_t const instanceStart;
5319/// uint32_t const instanceSize;
5320/// uint32_t const reserved; // only when building for 64bit targets
5321/// const uint8_t * const ivarLayout;
5322/// const char *const name;
5323/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005324/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005325/// const struct _ivar_list_t *const ivars;
5326/// const uint8_t * const weakIvarLayout;
5327/// const struct _prop_list_t * const properties;
5328/// }
5329
5330/// struct _class_t {
5331/// struct _class_t *isa;
5332/// struct _class_t * const superclass;
5333/// void *cache;
5334/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005335/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005336/// }
5337
5338/// struct _category_t {
5339/// const char * const name;
5340/// struct _class_t *const cls;
5341/// const struct _method_list_t * const instance_methods;
5342/// const struct _method_list_t * const class_methods;
5343/// const struct _protocol_list_t * const protocols;
5344/// const struct _prop_list_t * const properties;
5345/// }
5346
5347/// MessageRefTy - LLVM for:
5348/// struct _message_ref_t {
5349/// IMP messenger;
5350/// SEL name;
5351/// };
5352
5353/// SuperMessageRefTy - LLVM for:
5354/// struct _super_message_ref_t {
5355/// SUPER_IMP messenger;
5356/// SEL name;
5357/// };
5358
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005359static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005360 static bool meta_data_declared = false;
5361 if (meta_data_declared)
5362 return;
5363
5364 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005365 Result += "\tconst char *name;\n";
5366 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 Result += "};\n";
5368
5369 Result += "\nstruct _protocol_t;\n";
5370
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005371 Result += "\nstruct _objc_method {\n";
5372 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005373 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005374 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005375 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005376
5377 Result += "\nstruct _protocol_t {\n";
5378 Result += "\tvoid * isa; // NULL\n";
5379 Result += "\tconst char * const protocol_name;\n";
5380 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5381 Result += "\tconst struct method_list_t * const instance_methods;\n";
5382 Result += "\tconst struct method_list_t * const class_methods;\n";
5383 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5384 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5385 Result += "\tconst struct _prop_list_t * properties;\n";
5386 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5387 Result += "\tconst unsigned int flags; // = 0\n";
5388 Result += "\tconst char ** extendedMethodTypes;\n";
5389 Result += "};\n";
5390
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005391 Result += "\nstruct _ivar_t {\n";
5392 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005393 Result += "\tconst char *name;\n";
5394 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005395 Result += "\tunsigned int alignment;\n";
5396 Result += "\tunsigned int size;\n";
5397 Result += "};\n";
5398
5399 Result += "\nstruct _class_ro_t {\n";
5400 Result += "\tunsigned int const flags;\n";
5401 Result += "\tunsigned int instanceStart;\n";
5402 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005403 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5404 if (Triple.getArch() == llvm::Triple::x86_64)
5405 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005406 Result += "\tconst unsigned char * const ivarLayout;\n";
5407 Result += "\tconst char *const name;\n";
5408 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5409 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5410 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5411 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5412 Result += "\tconst struct _prop_list_t *const properties;\n";
5413 Result += "};\n";
5414
5415 Result += "\nstruct _class_t {\n";
5416 Result += "\tstruct _class_t *isa;\n";
5417 Result += "\tstruct _class_t *const superclass;\n";
5418 Result += "\tvoid *cache;\n";
5419 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005420 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005421 Result += "};\n";
5422
5423 Result += "\nstruct _category_t {\n";
5424 Result += "\tconst char * const name;\n";
5425 Result += "\tstruct _class_t *const cls;\n";
5426 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5427 Result += "\tconst struct _method_list_t *const class_methods;\n";
5428 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5429 Result += "\tconst struct _prop_list_t *const properties;\n";
5430 Result += "};\n";
5431
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005432 Result += "extern void *_objc_empty_cache;\n";
5433 Result += "extern void *_objc_empty_vtable;\n";
5434
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005435 meta_data_declared = true;
5436}
5437
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005438static void Write_protocol_list_t_TypeDecl(std::string &Result,
5439 long super_protocol_count) {
5440 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5441 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5442 Result += "\tstruct _protocol_t *super_protocols[";
5443 Result += utostr(super_protocol_count); Result += "];\n";
5444 Result += "}";
5445}
5446
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005447static void Write_method_list_t_TypeDecl(std::string &Result,
5448 unsigned int method_count) {
5449 Result += "struct /*_method_list_t*/"; Result += " {\n";
5450 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5451 Result += "\tunsigned int method_count;\n";
5452 Result += "\tstruct _objc_method method_list[";
5453 Result += utostr(method_count); Result += "];\n";
5454 Result += "}";
5455}
5456
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005457static void Write__prop_list_t_TypeDecl(std::string &Result,
5458 unsigned int property_count) {
5459 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5460 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5461 Result += "\tunsigned int count_of_properties;\n";
5462 Result += "\tstruct _prop_t prop_list[";
5463 Result += utostr(property_count); Result += "];\n";
5464 Result += "}";
5465}
5466
Fariborz Jahanianae932952012-02-10 20:47:10 +00005467static void Write__ivar_list_t_TypeDecl(std::string &Result,
5468 unsigned int ivar_count) {
5469 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5470 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5471 Result += "\tunsigned int count;\n";
5472 Result += "\tstruct _ivar_t ivar_list[";
5473 Result += utostr(ivar_count); Result += "];\n";
5474 Result += "}";
5475}
5476
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005477static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5478 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5479 StringRef VarName,
5480 StringRef ProtocolName) {
5481 if (SuperProtocols.size() > 0) {
5482 Result += "\nstatic ";
5483 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5484 Result += " "; Result += VarName;
5485 Result += ProtocolName;
5486 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5487 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5488 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5489 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5490 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5491 Result += SuperPD->getNameAsString();
5492 if (i == e-1)
5493 Result += "\n};\n";
5494 else
5495 Result += ",\n";
5496 }
5497 }
5498}
5499
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005500static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5501 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005502 ArrayRef<ObjCMethodDecl *> Methods,
5503 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005504 StringRef TopLevelDeclName,
5505 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005506 if (Methods.size() > 0) {
5507 Result += "\nstatic ";
5508 Write_method_list_t_TypeDecl(Result, Methods.size());
5509 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005510 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005511 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5512 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5513 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5514 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5515 ObjCMethodDecl *MD = Methods[i];
5516 if (i == 0)
5517 Result += "\t{{(struct objc_selector *)\"";
5518 else
5519 Result += "\t{(struct objc_selector *)\"";
5520 Result += (MD)->getSelector().getAsString(); Result += "\"";
5521 Result += ", ";
5522 std::string MethodTypeString;
5523 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5524 Result += "\""; Result += MethodTypeString; Result += "\"";
5525 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005526 if (!MethodImpl)
5527 Result += "0";
5528 else {
5529 Result += "(void *)";
5530 Result += RewriteObj.MethodInternalNames[MD];
5531 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005532 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005533 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005534 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005535 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005536 }
5537 Result += "};\n";
5538 }
5539}
5540
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005541static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005542 ASTContext *Context, std::string &Result,
5543 ArrayRef<ObjCPropertyDecl *> Properties,
5544 const Decl *Container,
5545 StringRef VarName,
5546 StringRef ProtocolName) {
5547 if (Properties.size() > 0) {
5548 Result += "\nstatic ";
5549 Write__prop_list_t_TypeDecl(Result, Properties.size());
5550 Result += " "; Result += VarName;
5551 Result += ProtocolName;
5552 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5553 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5554 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5555 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5556 ObjCPropertyDecl *PropDecl = Properties[i];
5557 if (i == 0)
5558 Result += "\t{{\"";
5559 else
5560 Result += "\t{\"";
5561 Result += PropDecl->getName(); Result += "\",";
5562 std::string PropertyTypeString, QuotePropertyTypeString;
5563 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5564 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5565 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5566 if (i == e-1)
5567 Result += "}}\n";
5568 else
5569 Result += "},\n";
5570 }
5571 Result += "};\n";
5572 }
5573}
5574
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005575// Metadata flags
5576enum MetaDataDlags {
5577 CLS = 0x0,
5578 CLS_META = 0x1,
5579 CLS_ROOT = 0x2,
5580 OBJC2_CLS_HIDDEN = 0x10,
5581 CLS_EXCEPTION = 0x20,
5582
5583 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5584 CLS_HAS_IVAR_RELEASER = 0x40,
5585 /// class was compiled with -fobjc-arr
5586 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5587};
5588
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005589static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5590 unsigned int flags,
5591 const std::string &InstanceStart,
5592 const std::string &InstanceSize,
5593 ArrayRef<ObjCMethodDecl *>baseMethods,
5594 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5595 ArrayRef<ObjCIvarDecl *>ivars,
5596 ArrayRef<ObjCPropertyDecl *>Properties,
5597 StringRef VarName,
5598 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005599 Result += "\nstatic struct _class_ro_t ";
5600 Result += VarName; Result += ClassName;
5601 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5602 Result += "\t";
5603 Result += llvm::utostr(flags); Result += ", ";
5604 Result += InstanceStart; Result += ", ";
5605 Result += InstanceSize; Result += ", \n";
5606 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005607 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5608 if (Triple.getArch() == llvm::Triple::x86_64)
5609 // uint32_t const reserved; // only when building for 64bit targets
5610 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005611 // const uint8_t * const ivarLayout;
5612 Result += "0, \n\t";
5613 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005614 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005615 if (baseMethods.size() > 0) {
5616 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005617 if (metaclass)
5618 Result += "_OBJC_$_CLASS_METHODS_";
5619 else
5620 Result += "_OBJC_$_INSTANCE_METHODS_";
5621 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005622 Result += ",\n\t";
5623 }
5624 else
5625 Result += "0, \n\t";
5626
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005627 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005628 Result += "(const struct _objc_protocol_list *)&";
5629 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5630 Result += ",\n\t";
5631 }
5632 else
5633 Result += "0, \n\t";
5634
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005635 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005636 Result += "(const struct _ivar_list_t *)&";
5637 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5638 Result += ",\n\t";
5639 }
5640 else
5641 Result += "0, \n\t";
5642
5643 // weakIvarLayout
5644 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005645 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005646 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005647 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005648 Result += ",\n";
5649 }
5650 else
5651 Result += "0, \n";
5652
5653 Result += "};\n";
5654}
5655
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005656static void Write_class_t(ASTContext *Context, std::string &Result,
5657 StringRef VarName,
5658 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005659
5660 if (metadata && !CDecl->getSuperClass()) {
5661 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005662 Result += "\n";
5663 if (CDecl->getImplementation())
5664 Result += "__declspec(dllexport) ";
5665 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005666 Result += CDecl->getNameAsString();
5667 Result += ";\n";
5668 }
5669 // Also, for possibility of 'super' metadata class not having been defined yet.
5670 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005671 Result += "\n";
5672 if (CDecl->getSuperClass()->getImplementation())
5673 Result += "__declspec(dllexport) ";
5674 Result += "extern struct _class_t ";
5675 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005676 Result += CDecl->getSuperClass()->getNameAsString();
5677 Result += ";\n";
5678 }
5679
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005680 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005681 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5682 Result += "\t";
5683 if (metadata) {
5684 if (CDecl->getSuperClass()) {
5685 Result += "&"; Result += VarName;
5686 Result += CDecl->getSuperClass()->getNameAsString();
5687 Result += ",\n\t";
5688 Result += "&"; Result += VarName;
5689 Result += CDecl->getSuperClass()->getNameAsString();
5690 Result += ",\n\t";
5691 }
5692 else {
5693 Result += "&"; Result += VarName;
5694 Result += CDecl->getNameAsString();
5695 Result += ",\n\t";
5696 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5697 Result += ",\n\t";
5698 }
5699 }
5700 else {
5701 Result += "&OBJC_METACLASS_$_";
5702 Result += CDecl->getNameAsString();
5703 Result += ",\n\t";
5704 if (CDecl->getSuperClass()) {
5705 Result += "&"; Result += VarName;
5706 Result += CDecl->getSuperClass()->getNameAsString();
5707 Result += ",\n\t";
5708 }
5709 else
5710 Result += "0,\n\t";
5711 }
5712 Result += "(void *)&_objc_empty_cache,\n\t";
5713 Result += "(void *)&_objc_empty_vtable,\n\t";
5714 if (metadata)
5715 Result += "&_OBJC_METACLASS_RO_$_";
5716 else
5717 Result += "&_OBJC_CLASS_RO_$_";
5718 Result += CDecl->getNameAsString();
5719 Result += ",\n};\n";
5720}
5721
Fariborz Jahanian61186122012-02-17 18:40:41 +00005722static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5723 std::string &Result,
5724 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005725 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005726 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5727 ArrayRef<ObjCMethodDecl *> ClassMethods,
5728 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5729 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005730
5731 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005732 // must declare an extern class object in case this class is not implemented
5733 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005734 Result += "\n";
5735 if (ClassDecl->getImplementation())
5736 Result += "__declspec(dllexport) ";
5737
5738 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005739 Result += "OBJC_CLASS_$_"; Result += ClassName;
5740 Result += ";\n";
5741
Fariborz Jahanian61186122012-02-17 18:40:41 +00005742 Result += "\nstatic struct _category_t ";
5743 Result += "_OBJC_$_CATEGORY_";
5744 Result += ClassName; Result += "_$_"; Result += CatName;
5745 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5746 Result += "{\n";
5747 Result += "\t\""; Result += ClassName; Result += "\",\n";
5748 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5749 Result += ",\n";
5750 if (InstanceMethods.size() > 0) {
5751 Result += "\t(const struct _method_list_t *)&";
5752 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5753 Result += ClassName; Result += "_$_"; Result += CatName;
5754 Result += ",\n";
5755 }
5756 else
5757 Result += "\t0,\n";
5758
5759 if (ClassMethods.size() > 0) {
5760 Result += "\t(const struct _method_list_t *)&";
5761 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5762 Result += ClassName; Result += "_$_"; Result += CatName;
5763 Result += ",\n";
5764 }
5765 else
5766 Result += "\t0,\n";
5767
5768 if (RefedProtocols.size() > 0) {
5769 Result += "\t(const struct _protocol_list_t *)&";
5770 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5771 Result += ClassName; Result += "_$_"; Result += CatName;
5772 Result += ",\n";
5773 }
5774 else
5775 Result += "\t0,\n";
5776
5777 if (ClassProperties.size() > 0) {
5778 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5779 Result += ClassName; Result += "_$_"; Result += CatName;
5780 Result += ",\n";
5781 }
5782 else
5783 Result += "\t0,\n";
5784
5785 Result += "};\n";
5786}
5787
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005788static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5789 ASTContext *Context, std::string &Result,
5790 ArrayRef<ObjCMethodDecl *> Methods,
5791 StringRef VarName,
5792 StringRef ProtocolName) {
5793 if (Methods.size() == 0)
5794 return;
5795
5796 Result += "\nstatic const char *";
5797 Result += VarName; Result += ProtocolName;
5798 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5799 Result += "{\n";
5800 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5801 ObjCMethodDecl *MD = Methods[i];
5802 std::string MethodTypeString, QuoteMethodTypeString;
5803 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5804 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5805 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5806 if (i == e-1)
5807 Result += "\n};\n";
5808 else {
5809 Result += ",\n";
5810 }
5811 }
5812}
5813
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005814static void Write_IvarOffsetVar(ASTContext *Context,
5815 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005816 ArrayRef<ObjCIvarDecl *> Ivars,
5817 StringRef VarName,
5818 StringRef ClassName) {
5819 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5820 // this is what happens:
5821 /**
5822 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5823 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5824 Class->getVisibility() == HiddenVisibility)
5825 Visibility shoud be: HiddenVisibility;
5826 else
5827 Visibility shoud be: DefaultVisibility;
5828 */
5829
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005830 Result += "\n";
5831 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5832 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005833 if (Context->getLangOpts().MicrosoftExt)
5834 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5835
5836 if (!Context->getLangOpts().MicrosoftExt ||
5837 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005838 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005839 Result += "unsigned long int ";
5840 else
5841 Result += "__declspec(dllexport) unsigned long int ";
5842
5843 Result += VarName;
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005844 Result += ClassName; Result += "_";
5845 Result += IvarDecl->getName();
5846 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5847 Result += " = ";
5848 if (IvarDecl->isBitField()) {
5849 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5850 // place all bitfields at offset 0.
5851 Result += "0;\n";
5852 }
5853 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005854 Result += "__OFFSETOFIVAR__(struct ";
5855 Result += ClassName;
5856 Result += "_IMPL, ";
5857 Result += IvarDecl->getName(); Result += ");\n";
5858 }
5859 }
5860}
5861
Fariborz Jahanianae932952012-02-10 20:47:10 +00005862static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5863 ASTContext *Context, std::string &Result,
5864 ArrayRef<ObjCIvarDecl *> Ivars,
5865 StringRef VarName,
5866 StringRef ClassName) {
5867 if (Ivars.size() > 0) {
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005868 Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005869
Fariborz Jahanianae932952012-02-10 20:47:10 +00005870 Result += "\nstatic ";
5871 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5872 Result += " "; Result += VarName;
5873 Result += ClassName;
5874 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5875 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5876 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5877 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5878 ObjCIvarDecl *IvarDecl = Ivars[i];
5879 if (i == 0)
5880 Result += "\t{{";
5881 else
5882 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005883
5884 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5885 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5886 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005887
5888 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5889 std::string IvarTypeString, QuoteIvarTypeString;
5890 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5891 IvarDecl);
5892 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5893 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5894
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005895 // FIXME. this alignment represents the host alignment and need be changed to
5896 // represent the target alignment.
5897 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5898 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005899 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005900 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5901 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005902 if (i == e-1)
5903 Result += "}}\n";
5904 else
5905 Result += "},\n";
5906 }
5907 Result += "};\n";
5908 }
5909}
5910
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005911/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005912void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5913 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005915 // Do not synthesize the protocol more than once.
5916 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5917 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005918 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005919
5920 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5921 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005922 // Must write out all protocol definitions in current qualifier list,
5923 // and in their nested qualifiers before writing out current definition.
5924 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5925 E = PDecl->protocol_end(); I != E; ++I)
5926 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005927
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005928 // Construct method lists.
5929 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5930 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5931 for (ObjCProtocolDecl::instmeth_iterator
5932 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5933 I != E; ++I) {
5934 ObjCMethodDecl *MD = *I;
5935 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5936 OptInstanceMethods.push_back(MD);
5937 } else {
5938 InstanceMethods.push_back(MD);
5939 }
5940 }
5941
5942 for (ObjCProtocolDecl::classmeth_iterator
5943 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5944 I != E; ++I) {
5945 ObjCMethodDecl *MD = *I;
5946 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5947 OptClassMethods.push_back(MD);
5948 } else {
5949 ClassMethods.push_back(MD);
5950 }
5951 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005952 std::vector<ObjCMethodDecl *> AllMethods;
5953 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5954 AllMethods.push_back(InstanceMethods[i]);
5955 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5956 AllMethods.push_back(ClassMethods[i]);
5957 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5958 AllMethods.push_back(OptInstanceMethods[i]);
5959 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5960 AllMethods.push_back(OptClassMethods[i]);
5961
5962 Write__extendedMethodTypes_initializer(*this, Context, Result,
5963 AllMethods,
5964 "_OBJC_PROTOCOL_METHOD_TYPES_",
5965 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005966 // Protocol's super protocol list
5967 std::vector<ObjCProtocolDecl *> SuperProtocols;
5968 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5969 E = PDecl->protocol_end(); I != E; ++I)
5970 SuperProtocols.push_back(*I);
5971
5972 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5973 "_OBJC_PROTOCOL_REFS_",
5974 PDecl->getNameAsString());
5975
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005976 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005977 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005978 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005979
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005980 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005981 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005982 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005983
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005984 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005985 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005986 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005987
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005988 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005989 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005990 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005991
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005992 // Protocol's property metadata.
5993 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5994 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5995 E = PDecl->prop_end(); I != E; ++I)
5996 ProtocolProperties.push_back(*I);
5997
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005998 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005999 /* Container */0,
6000 "_OBJC_PROTOCOL_PROPERTIES_",
6001 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006002
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006003 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006004 Result += "\n";
6005 if (LangOpts.MicrosoftExt)
6006 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006007 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006008 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006009 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6010 Result += "\t0,\n"; // id is; is null
6011 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006012 if (SuperProtocols.size() > 0) {
6013 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6014 Result += PDecl->getNameAsString(); Result += ",\n";
6015 }
6016 else
6017 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006018 if (InstanceMethods.size() > 0) {
6019 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6020 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006021 }
6022 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006023 Result += "\t0,\n";
6024
6025 if (ClassMethods.size() > 0) {
6026 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6027 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006028 }
6029 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006030 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006031
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006032 if (OptInstanceMethods.size() > 0) {
6033 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6034 Result += PDecl->getNameAsString(); Result += ",\n";
6035 }
6036 else
6037 Result += "\t0,\n";
6038
6039 if (OptClassMethods.size() > 0) {
6040 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6041 Result += PDecl->getNameAsString(); Result += ",\n";
6042 }
6043 else
6044 Result += "\t0,\n";
6045
6046 if (ProtocolProperties.size() > 0) {
6047 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6048 Result += PDecl->getNameAsString(); Result += ",\n";
6049 }
6050 else
6051 Result += "\t0,\n";
6052
6053 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6054 Result += "\t0,\n";
6055
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006056 if (AllMethods.size() > 0) {
6057 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6058 Result += PDecl->getNameAsString();
6059 Result += "\n};\n";
6060 }
6061 else
6062 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006063
6064 // Use this protocol meta-data to build protocol list table in section
6065 // .objc_protolist$B
6066 // Unspecified visibility means 'private extern'.
6067 if (LangOpts.MicrosoftExt)
6068 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6069 Result += "struct _protocol_t *";
6070 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6071 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6072 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006073
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006074 // Mark this protocol as having been generated.
6075 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6076 llvm_unreachable("protocol already synthesized");
6077
6078}
6079
6080void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6081 const ObjCList<ObjCProtocolDecl> &Protocols,
6082 StringRef prefix, StringRef ClassName,
6083 std::string &Result) {
6084 if (Protocols.empty()) return;
6085
6086 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006087 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006088
6089 // Output the top lovel protocol meta-data for the class.
6090 /* struct _objc_protocol_list {
6091 struct _objc_protocol_list *next;
6092 int protocol_count;
6093 struct _objc_protocol *class_protocols[];
6094 }
6095 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006096 Result += "\n";
6097 if (LangOpts.MicrosoftExt)
6098 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6099 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006100 Result += "\tstruct _objc_protocol_list *next;\n";
6101 Result += "\tint protocol_count;\n";
6102 Result += "\tstruct _objc_protocol *class_protocols[";
6103 Result += utostr(Protocols.size());
6104 Result += "];\n} _OBJC_";
6105 Result += prefix;
6106 Result += "_PROTOCOLS_";
6107 Result += ClassName;
6108 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6109 "{\n\t0, ";
6110 Result += utostr(Protocols.size());
6111 Result += "\n";
6112
6113 Result += "\t,{&_OBJC_PROTOCOL_";
6114 Result += Protocols[0]->getNameAsString();
6115 Result += " \n";
6116
6117 for (unsigned i = 1; i != Protocols.size(); i++) {
6118 Result += "\t ,&_OBJC_PROTOCOL_";
6119 Result += Protocols[i]->getNameAsString();
6120 Result += "\n";
6121 }
6122 Result += "\t }\n};\n";
6123}
6124
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006125/// hasObjCExceptionAttribute - Return true if this class or any super
6126/// class has the __objc_exception__ attribute.
6127/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6128static bool hasObjCExceptionAttribute(ASTContext &Context,
6129 const ObjCInterfaceDecl *OID) {
6130 if (OID->hasAttr<ObjCExceptionAttr>())
6131 return true;
6132 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6133 return hasObjCExceptionAttribute(Context, Super);
6134 return false;
6135}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006137void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6138 std::string &Result) {
6139 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6140
6141 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006142 if (CDecl->isImplicitInterfaceDecl())
6143 assert(false &&
6144 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006145
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006146 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006147 SmallVector<ObjCIvarDecl *, 8> IVars;
6148
6149 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6150 IVD; IVD = IVD->getNextIvar()) {
6151 // Ignore unnamed bit-fields.
6152 if (!IVD->getDeclName())
6153 continue;
6154 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006155 }
6156
Fariborz Jahanianae932952012-02-10 20:47:10 +00006157 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006158 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006159 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006160
6161 // Build _objc_method_list for class's instance methods if needed
6162 SmallVector<ObjCMethodDecl *, 32>
6163 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6164
6165 // If any of our property implementations have associated getters or
6166 // setters, produce metadata for them as well.
6167 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6168 PropEnd = IDecl->propimpl_end();
6169 Prop != PropEnd; ++Prop) {
6170 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6171 continue;
6172 if (!(*Prop)->getPropertyIvarDecl())
6173 continue;
6174 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6175 if (!PD)
6176 continue;
6177 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6178 if (!Getter->isDefined())
6179 InstanceMethods.push_back(Getter);
6180 if (PD->isReadOnly())
6181 continue;
6182 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6183 if (!Setter->isDefined())
6184 InstanceMethods.push_back(Setter);
6185 }
6186
6187 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6188 "_OBJC_$_INSTANCE_METHODS_",
6189 IDecl->getNameAsString(), true);
6190
6191 SmallVector<ObjCMethodDecl *, 32>
6192 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6193
6194 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6195 "_OBJC_$_CLASS_METHODS_",
6196 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006197
6198 // Protocols referenced in class declaration?
6199 // Protocol's super protocol list
6200 std::vector<ObjCProtocolDecl *> RefedProtocols;
6201 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6202 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6203 E = Protocols.end();
6204 I != E; ++I) {
6205 RefedProtocols.push_back(*I);
6206 // Must write out all protocol definitions in current qualifier list,
6207 // and in their nested qualifiers before writing out current definition.
6208 RewriteObjCProtocolMetaData(*I, Result);
6209 }
6210
6211 Write_protocol_list_initializer(Context, Result,
6212 RefedProtocols,
6213 "_OBJC_CLASS_PROTOCOLS_$_",
6214 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006215
6216 // Protocol's property metadata.
6217 std::vector<ObjCPropertyDecl *> ClassProperties;
6218 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6219 E = CDecl->prop_end(); I != E; ++I)
6220 ClassProperties.push_back(*I);
6221
6222 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6223 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006224 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006225 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006226
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006227
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006228 // Data for initializing _class_ro_t metaclass meta-data
6229 uint32_t flags = CLS_META;
6230 std::string InstanceSize;
6231 std::string InstanceStart;
6232
6233
6234 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6235 if (classIsHidden)
6236 flags |= OBJC2_CLS_HIDDEN;
6237
6238 if (!CDecl->getSuperClass())
6239 // class is root
6240 flags |= CLS_ROOT;
6241 InstanceSize = "sizeof(struct _class_t)";
6242 InstanceStart = InstanceSize;
6243 Write__class_ro_t_initializer(Context, Result, flags,
6244 InstanceStart, InstanceSize,
6245 ClassMethods,
6246 0,
6247 0,
6248 0,
6249 "_OBJC_METACLASS_RO_$_",
6250 CDecl->getNameAsString());
6251
6252
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006253 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006254 flags = CLS;
6255 if (classIsHidden)
6256 flags |= OBJC2_CLS_HIDDEN;
6257
6258 if (hasObjCExceptionAttribute(*Context, CDecl))
6259 flags |= CLS_EXCEPTION;
6260
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006261 if (!CDecl->getSuperClass())
6262 // class is root
6263 flags |= CLS_ROOT;
6264
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006265 InstanceSize.clear();
6266 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006267 if (!ObjCSynthesizedStructs.count(CDecl)) {
6268 InstanceSize = "0";
6269 InstanceStart = "0";
6270 }
6271 else {
6272 InstanceSize = "sizeof(struct ";
6273 InstanceSize += CDecl->getNameAsString();
6274 InstanceSize += "_IMPL)";
6275
6276 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6277 if (IVD) {
6278 InstanceStart += "__OFFSETOFIVAR__(struct ";
6279 InstanceStart += CDecl->getNameAsString();
6280 InstanceStart += "_IMPL, ";
6281 InstanceStart += IVD->getNameAsString();
6282 InstanceStart += ")";
6283 }
6284 else
6285 InstanceStart = InstanceSize;
6286 }
6287 Write__class_ro_t_initializer(Context, Result, flags,
6288 InstanceStart, InstanceSize,
6289 InstanceMethods,
6290 RefedProtocols,
6291 IVars,
6292 ClassProperties,
6293 "_OBJC_CLASS_RO_$_",
6294 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006295
6296 Write_class_t(Context, Result,
6297 "OBJC_METACLASS_$_",
6298 CDecl, /*metaclass*/true);
6299
6300 Write_class_t(Context, Result,
6301 "OBJC_CLASS_$_",
6302 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006303
6304 if (ImplementationIsNonLazy(IDecl))
6305 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006306
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006307}
6308
6309void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6310 int ClsDefCount = ClassImplementation.size();
6311 int CatDefCount = CategoryImplementation.size();
6312
6313 // For each implemented class, write out all its meta data.
6314 for (int i = 0; i < ClsDefCount; i++)
6315 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6316
6317 // For each implemented category, write out all its meta data.
6318 for (int i = 0; i < CatDefCount; i++)
6319 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6320
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006321 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006322 if (LangOpts.MicrosoftExt)
6323 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006324 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6325 Result += llvm::utostr(ClsDefCount); Result += "]";
6326 Result +=
6327 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6328 "regular,no_dead_strip\")))= {\n";
6329 for (int i = 0; i < ClsDefCount; i++) {
6330 Result += "\t&OBJC_CLASS_$_";
6331 Result += ClassImplementation[i]->getNameAsString();
6332 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006333 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006334 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006335
6336 if (!DefinedNonLazyClasses.empty()) {
6337 if (LangOpts.MicrosoftExt)
6338 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6339 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6340 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6341 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6342 Result += ",\n";
6343 }
6344 Result += "};\n";
6345 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006346 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006347
6348 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006349 if (LangOpts.MicrosoftExt)
6350 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006351 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6352 Result += llvm::utostr(CatDefCount); Result += "]";
6353 Result +=
6354 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6355 "regular,no_dead_strip\")))= {\n";
6356 for (int i = 0; i < CatDefCount; i++) {
6357 Result += "\t&_OBJC_$_CATEGORY_";
6358 Result +=
6359 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6360 Result += "_$_";
6361 Result += CategoryImplementation[i]->getNameAsString();
6362 Result += ",\n";
6363 }
6364 Result += "};\n";
6365 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006366
6367 if (!DefinedNonLazyCategories.empty()) {
6368 if (LangOpts.MicrosoftExt)
6369 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6370 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6371 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6372 Result += "\t&_OBJC_$_CATEGORY_";
6373 Result +=
6374 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6375 Result += "_$_";
6376 Result += DefinedNonLazyCategories[i]->getNameAsString();
6377 Result += ",\n";
6378 }
6379 Result += "};\n";
6380 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006381}
6382
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006383void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6384 if (LangOpts.MicrosoftExt)
6385 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6386
6387 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6388 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006389 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006390}
6391
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6393/// implementation.
6394void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6395 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006396 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006397 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6398 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006399 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006400 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6401 CDecl = CDecl->getNextClassCategory())
6402 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6403 break;
6404
6405 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006406 FullCategoryName += "_$_";
6407 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006408
6409 // Build _objc_method_list for class's instance methods if needed
6410 SmallVector<ObjCMethodDecl *, 32>
6411 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6412
6413 // If any of our property implementations have associated getters or
6414 // setters, produce metadata for them as well.
6415 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6416 PropEnd = IDecl->propimpl_end();
6417 Prop != PropEnd; ++Prop) {
6418 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6419 continue;
6420 if (!(*Prop)->getPropertyIvarDecl())
6421 continue;
6422 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6423 if (!PD)
6424 continue;
6425 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6426 InstanceMethods.push_back(Getter);
6427 if (PD->isReadOnly())
6428 continue;
6429 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6430 InstanceMethods.push_back(Setter);
6431 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006432
Fariborz Jahanian61186122012-02-17 18:40:41 +00006433 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6434 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6435 FullCategoryName, true);
6436
6437 SmallVector<ObjCMethodDecl *, 32>
6438 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6439
6440 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6441 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6442 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006443
6444 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006445 // Protocol's super protocol list
6446 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006447 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6448 E = CDecl->protocol_end();
6449
6450 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006451 RefedProtocols.push_back(*I);
6452 // Must write out all protocol definitions in current qualifier list,
6453 // and in their nested qualifiers before writing out current definition.
6454 RewriteObjCProtocolMetaData(*I, Result);
6455 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006456
Fariborz Jahanian61186122012-02-17 18:40:41 +00006457 Write_protocol_list_initializer(Context, Result,
6458 RefedProtocols,
6459 "_OBJC_CATEGORY_PROTOCOLS_$_",
6460 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006461
Fariborz Jahanian61186122012-02-17 18:40:41 +00006462 // Protocol's property metadata.
6463 std::vector<ObjCPropertyDecl *> ClassProperties;
6464 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6465 E = CDecl->prop_end(); I != E; ++I)
6466 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006467
Fariborz Jahanian61186122012-02-17 18:40:41 +00006468 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6469 /* Container */0,
6470 "_OBJC_$_PROP_LIST_",
6471 FullCategoryName);
6472
6473 Write_category_t(*this, Context, Result,
6474 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006475 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006476 InstanceMethods,
6477 ClassMethods,
6478 RefedProtocols,
6479 ClassProperties);
6480
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006481 // Determine if this category is also "non-lazy".
6482 if (ImplementationIsNonLazy(IDecl))
6483 DefinedNonLazyCategories.push_back(CDecl);
6484
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006485}
6486
6487// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6488/// class methods.
6489template<typename MethodIterator>
6490void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6491 MethodIterator MethodEnd,
6492 bool IsInstanceMethod,
6493 StringRef prefix,
6494 StringRef ClassName,
6495 std::string &Result) {
6496 if (MethodBegin == MethodEnd) return;
6497
6498 if (!objc_impl_method) {
6499 /* struct _objc_method {
6500 SEL _cmd;
6501 char *method_types;
6502 void *_imp;
6503 }
6504 */
6505 Result += "\nstruct _objc_method {\n";
6506 Result += "\tSEL _cmd;\n";
6507 Result += "\tchar *method_types;\n";
6508 Result += "\tvoid *_imp;\n";
6509 Result += "};\n";
6510
6511 objc_impl_method = true;
6512 }
6513
6514 // Build _objc_method_list for class's methods if needed
6515
6516 /* struct {
6517 struct _objc_method_list *next_method;
6518 int method_count;
6519 struct _objc_method method_list[];
6520 }
6521 */
6522 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006523 Result += "\n";
6524 if (LangOpts.MicrosoftExt) {
6525 if (IsInstanceMethod)
6526 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6527 else
6528 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6529 }
6530 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006531 Result += "\tstruct _objc_method_list *next_method;\n";
6532 Result += "\tint method_count;\n";
6533 Result += "\tstruct _objc_method method_list[";
6534 Result += utostr(NumMethods);
6535 Result += "];\n} _OBJC_";
6536 Result += prefix;
6537 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6538 Result += "_METHODS_";
6539 Result += ClassName;
6540 Result += " __attribute__ ((used, section (\"__OBJC, __";
6541 Result += IsInstanceMethod ? "inst" : "cls";
6542 Result += "_meth\")))= ";
6543 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6544
6545 Result += "\t,{{(SEL)\"";
6546 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6547 std::string MethodTypeString;
6548 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6549 Result += "\", \"";
6550 Result += MethodTypeString;
6551 Result += "\", (void *)";
6552 Result += MethodInternalNames[*MethodBegin];
6553 Result += "}\n";
6554 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6555 Result += "\t ,{(SEL)\"";
6556 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6557 std::string MethodTypeString;
6558 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6559 Result += "\", \"";
6560 Result += MethodTypeString;
6561 Result += "\", (void *)";
6562 Result += MethodInternalNames[*MethodBegin];
6563 Result += "}\n";
6564 }
6565 Result += "\t }\n};\n";
6566}
6567
6568Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6569 SourceRange OldRange = IV->getSourceRange();
6570 Expr *BaseExpr = IV->getBase();
6571
6572 // Rewrite the base, but without actually doing replaces.
6573 {
6574 DisableReplaceStmtScope S(*this);
6575 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6576 IV->setBase(BaseExpr);
6577 }
6578
6579 ObjCIvarDecl *D = IV->getDecl();
6580
6581 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006582
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006583 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6584 const ObjCInterfaceType *iFaceDecl =
6585 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6586 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6587 // lookup which class implements the instance variable.
6588 ObjCInterfaceDecl *clsDeclared = 0;
6589 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6590 clsDeclared);
6591 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6592
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006593 // Build name of symbol holding ivar offset.
6594 std::string IvarOffsetName = "OBJC_IVAR_$_";
6595 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6596 IvarOffsetName += "_";
6597 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006598 ReferencedIvars[clsDeclared].insert(D);
6599
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006600 // cast offset to "char *".
6601 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6602 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006603 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006604 BaseExpr);
6605 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6606 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6607 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006608 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6609 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006610 SourceLocation());
6611 BinaryOperator *addExpr =
6612 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6613 Context->getPointerType(Context->CharTy),
6614 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006615 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006616 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6617 SourceLocation(),
6618 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006619 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006620 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006621 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006622
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006623 castExpr = NoTypeInfoCStyleCastExpr(Context,
6624 castT,
6625 CK_BitCast,
6626 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006627 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006628 VK_LValue, OK_Ordinary,
6629 SourceLocation());
6630 PE = new (Context) ParenExpr(OldRange.getBegin(),
6631 OldRange.getEnd(),
6632 Exp);
6633
6634 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006635 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006636
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006637 ReplaceStmtWithRange(IV, Replacement, OldRange);
6638 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006639}