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