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