blob: a9fe8cecd131fb6e9ab97b4d839f4c542b442585 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
106
107 /* Misc. containers needed for meta-data rewrite. */
108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000113 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000115 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
116 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117
118 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
119 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000121 SmallVector<Stmt *, 32> Stmts;
122 SmallVector<int, 8> ObjCBcLabelNo;
123 // Remember all the @protocol(<expr>) expressions.
124 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125
126 llvm::DenseSet<uint64_t> CopyDestroyCache;
127
128 // Block expressions.
129 SmallVector<BlockExpr *, 32> Blocks;
130 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
135 // Block related declarations.
136 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
138 SmallVector<ValueDecl *, 8> BlockByRefDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
140 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
141 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
142 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143
144 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000145 llvm::DenseMap<ObjCInterfaceDecl *,
146 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000148 // This maps an original source AST to it's rewritten form. This allows
149 // us to avoid rewriting the same node twice (which is very uncommon).
150 // This is needed to support some of the exotic property rewriting.
151 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152
153 // Needed for header files being rewritten
154 bool IsHeader;
155 bool SilenceRewriteMacroWarning;
156 bool objc_impl_method;
157
158 bool DisableReplaceStmt;
159 class DisableReplaceStmtScope {
160 RewriteModernObjC &R;
161 bool SavedValue;
162
163 public:
164 DisableReplaceStmtScope(RewriteModernObjC &R)
165 : R(R), SavedValue(R.DisableReplaceStmt) {
166 R.DisableReplaceStmt = true;
167 }
168 ~DisableReplaceStmtScope() {
169 R.DisableReplaceStmt = SavedValue;
170 }
171 };
172 void InitializeCommon(ASTContext &context);
173
174 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000175 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 // Top Level Driver code.
177 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
178 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
179 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
180 if (!Class->isThisDeclarationADefinition()) {
181 RewriteForwardClassDecl(D);
182 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000183 } else {
184 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000185 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000186 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 }
188 }
189
190 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
191 if (!Proto->isThisDeclarationADefinition()) {
192 RewriteForwardProtocolDecl(D);
193 break;
194 }
195 }
196
197 HandleTopLevelSingleDecl(*I);
198 }
199 return true;
200 }
201 void HandleTopLevelSingleDecl(Decl *D);
202 void HandleDeclInMainFile(Decl *D);
203 RewriteModernObjC(std::string inFile, raw_ostream *OS,
204 DiagnosticsEngine &D, const LangOptions &LOpts,
205 bool silenceMacroWarn);
206
207 ~RewriteModernObjC() {}
208
209 virtual void HandleTranslationUnit(ASTContext &C);
210
211 void ReplaceStmt(Stmt *Old, Stmt *New) {
212 Stmt *ReplacingStmt = ReplacedNodes[Old];
213
214 if (ReplacingStmt)
215 return; // We can't rewrite the same node twice.
216
217 if (DisableReplaceStmt)
218 return;
219
220 // If replacement succeeded or warning disabled return with no warning.
221 if (!Rewrite.ReplaceStmt(Old, New)) {
222 ReplacedNodes[Old] = New;
223 return;
224 }
225 if (SilenceRewriteMacroWarning)
226 return;
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 }
230
231 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
232 if (DisableReplaceStmt)
233 return;
234
235 // Measure the old text.
236 int Size = Rewrite.getRangeSize(SrcRange);
237 if (Size == -1) {
238 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
239 << Old->getSourceRange();
240 return;
241 }
242 // Get the new text.
243 std::string SStr;
244 llvm::raw_string_ostream S(SStr);
245 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
246 const std::string &Str = S.str();
247
248 // If replacement succeeded or warning disabled return with no warning.
249 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
250 ReplacedNodes[Old] = New;
251 return;
252 }
253 if (SilenceRewriteMacroWarning)
254 return;
255 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
256 << Old->getSourceRange();
257 }
258
259 void InsertText(SourceLocation Loc, StringRef Str,
260 bool InsertAfter = true) {
261 // If insertion succeeded or warning disabled return with no warning.
262 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
263 SilenceRewriteMacroWarning)
264 return;
265
266 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
267 }
268
269 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 StringRef Str) {
271 // If removal succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
273 SilenceRewriteMacroWarning)
274 return;
275
276 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
277 }
278
279 // Syntactic Rewriting.
280 void RewriteRecordBody(RecordDecl *RD);
281 void RewriteInclude();
282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
307 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
308 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
309 void RewriteTypeOfDecl(VarDecl *VD);
310 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
311
312 // Expression Rewriting.
313 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
314 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
315 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
318 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
319 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000320 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +0000321 Stmt *RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000322 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000323 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
326 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
327 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
328 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
329 SourceLocation OrigEnd);
330 Stmt *RewriteBreakStmt(BreakStmt *S);
331 Stmt *RewriteContinueStmt(ContinueStmt *S);
332 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000333 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334
335 // Block rewriting.
336 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
337
338 // Block specific rewrite rules.
339 void RewriteBlockPointerDecl(NamedDecl *VD);
340 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000341 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
343 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
344
345 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000348 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
349
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000350 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
351
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000352 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
353 std::string &Result);
354
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 virtual void Initialize(ASTContext &context);
356
357 // Misc. AST transformation routines. Somtimes they end up calling
358 // rewriting routines on the new ASTs.
359 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
360 Expr **args, unsigned nargs,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 void SynthCountByEnumWithState(std::string &buf);
369 void SynthMsgSendFunctionDecl();
370 void SynthMsgSendSuperFunctionDecl();
371 void SynthMsgSendStretFunctionDecl();
372 void SynthMsgSendFpretFunctionDecl();
373 void SynthMsgSendSuperStretFunctionDecl();
374 void SynthGetClassFunctionDecl();
375 void SynthGetMetaClassFunctionDecl();
376 void SynthGetSuperClassFunctionDecl();
377 void SynthSelGetUidFunctionDecl();
378 void SynthSuperContructorFunctionDecl();
379
380 // Rewriting metadata
381 template<typename MethodIterator>
382 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
383 MethodIterator MethodEnd,
384 bool IsInstanceMethod,
385 StringRef prefix,
386 StringRef ClassName,
387 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000388 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
389 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000390 virtual void RewriteObjCProtocolListMetaData(
391 const ObjCList<ObjCProtocolDecl> &Prots,
392 StringRef prefix, StringRef ClassName, std::string &Result);
393 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
394 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000395 virtual void RewriteClassSetupInitHook(std::string &Result);
396
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000397 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000398 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000399 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
400 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000401 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000402
403 // Rewriting ivar
404 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
405 std::string &Result);
406 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
407
408
409 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
410 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
411 StringRef funcName, std::string Tag);
412 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
413 StringRef funcName, std::string Tag);
414 std::string SynthesizeBlockImpl(BlockExpr *CE,
415 std::string Tag, std::string Desc);
416 std::string SynthesizeBlockDescriptor(std::string DescTag,
417 std::string ImplTag,
418 int i, StringRef funcName,
419 unsigned hasCopy);
420 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
421 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
422 StringRef FunName);
423 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
424 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000425 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426
427 // Misc. helper routines.
428 QualType getProtocolType();
429 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
431 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
432 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
433
434 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
435 void CollectBlockDeclRefInfo(BlockExpr *Exp);
436 void GetBlockDeclRefExprs(Stmt *S);
437 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000438 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000439 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
440
441 // We avoid calling Type::isBlockPointerType(), since it operates on the
442 // canonical type. We only care if the top-level type is a closure pointer.
443 bool isTopLevelBlockPointerType(QualType T) {
444 return isa<BlockPointerType>(T);
445 }
446
447 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
448 /// to a function pointer type and upon success, returns true; false
449 /// otherwise.
450 bool convertBlockPointerToFunctionPointer(QualType &T) {
451 if (isTopLevelBlockPointerType(T)) {
452 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
453 T = Context->getPointerType(BPT->getPointeeType());
454 return true;
455 }
456 return false;
457 }
458
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000459 bool convertObjCTypeToCStyleType(QualType &T);
460
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461 bool needToScanForQualifiers(QualType T);
462 QualType getSuperStructType();
463 QualType getConstantStringStructType();
464 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
465 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
466
467 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000468 if (T->isObjCQualifiedIdType()) {
469 bool isConst = T.isConstQualified();
470 T = isConst ? Context->getObjCIdType().withConst()
471 : Context->getObjCIdType();
472 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000473 else if (T->isObjCQualifiedClassType())
474 T = Context->getObjCClassType();
475 else if (T->isObjCObjectPointerType() &&
476 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
477 if (const ObjCObjectPointerType * OBJPT =
478 T->getAsObjCInterfacePointerType()) {
479 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
480 T = QualType(IFaceT, 0);
481 T = Context->getPointerType(T);
482 }
483 }
484 }
485
486 // FIXME: This predicate seems like it would be useful to add to ASTContext.
487 bool isObjCType(QualType T) {
488 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
489 return false;
490
491 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
492
493 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
494 OCT == Context->getCanonicalType(Context->getObjCClassType()))
495 return true;
496
497 if (const PointerType *PT = OCT->getAs<PointerType>()) {
498 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
499 PT->getPointeeType()->isObjCQualifiedIdType())
500 return true;
501 }
502 return false;
503 }
504 bool PointerTypeTakesAnyBlockArguments(QualType QT);
505 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
506 void GetExtentOfArgList(const char *Name, const char *&LParen,
507 const char *&RParen);
508
509 void QuoteDoublequotes(std::string &From, std::string &To) {
510 for (unsigned i = 0; i < From.length(); i++) {
511 if (From[i] == '"')
512 To += "\\\"";
513 else
514 To += From[i];
515 }
516 }
517
518 QualType getSimpleFunctionType(QualType result,
519 const QualType *args,
520 unsigned numArgs,
521 bool variadic = false) {
522 if (result == Context->getObjCInstanceType())
523 result = Context->getObjCIdType();
524 FunctionProtoType::ExtProtoInfo fpi;
525 fpi.Variadic = variadic;
526 return Context->getFunctionType(result, args, numArgs, fpi);
527 }
528
529 // Helper function: create a CStyleCastExpr with trivial type source info.
530 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
531 CastKind Kind, Expr *E) {
532 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
533 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
534 SourceLocation(), SourceLocation());
535 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000536
537 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
538 IdentifierInfo* II = &Context->Idents.get("load");
539 Selector LoadSel = Context->Selectors.getSelector(0, &II);
540 return OD->getClassMethod(LoadSel) != 0;
541 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000542 };
543
544}
545
546void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
548 if (const FunctionProtoType *fproto
549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
550 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
551 E = fproto->arg_type_end(); I && (I != E); ++I)
552 if (isTopLevelBlockPointerType(*I)) {
553 // All the args are checked/rewritten. Don't call twice!
554 RewriteBlockPointerDecl(D);
555 break;
556 }
557 }
558}
559
560void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
561 const PointerType *PT = funcType->getAs<PointerType>();
562 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
563 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
564}
565
566static bool IsHeaderFile(const std::string &Filename) {
567 std::string::size_type DotPos = Filename.rfind('.');
568
569 if (DotPos == std::string::npos) {
570 // no file extension
571 return false;
572 }
573
574 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 // C header: .h
576 // C++ header: .hh or .H;
577 return Ext == "h" || Ext == "hh" || Ext == "H";
578}
579
580RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
581 DiagnosticsEngine &D, const LangOptions &LOpts,
582 bool silenceMacroWarn)
583 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
584 SilenceRewriteMacroWarning(silenceMacroWarn) {
585 IsHeader = IsHeaderFile(inFile);
586 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
587 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000588 // FIXME. This should be an error. But if block is not called, it is OK. And it
589 // may break including some headers.
590 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting block literal declared in global scope is not implemented");
592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000593 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
594 DiagnosticsEngine::Warning,
595 "rewriter doesn't support user-specified control flow semantics "
596 "for @try/@finally (code may not execute properly)");
597}
598
599ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
600 raw_ostream* OS,
601 DiagnosticsEngine &Diags,
602 const LangOptions &LOpts,
603 bool SilenceRewriteMacroWarning) {
604 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
605}
606
607void RewriteModernObjC::InitializeCommon(ASTContext &context) {
608 Context = &context;
609 SM = &Context->getSourceManager();
610 TUDecl = Context->getTranslationUnitDecl();
611 MsgSendFunctionDecl = 0;
612 MsgSendSuperFunctionDecl = 0;
613 MsgSendStretFunctionDecl = 0;
614 MsgSendSuperStretFunctionDecl = 0;
615 MsgSendFpretFunctionDecl = 0;
616 GetClassFunctionDecl = 0;
617 GetMetaClassFunctionDecl = 0;
618 GetSuperClassFunctionDecl = 0;
619 SelGetUidFunctionDecl = 0;
620 CFStringFunctionDecl = 0;
621 ConstantStringClassReference = 0;
622 NSStringRecord = 0;
623 CurMethodDef = 0;
624 CurFunctionDef = 0;
625 CurFunctionDeclToDeclareForBlock = 0;
626 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000627 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000628 SuperStructDecl = 0;
629 ProtocolTypeDecl = 0;
630 ConstantStringDecl = 0;
631 BcLabelCount = 0;
632 SuperContructorFunctionDecl = 0;
633 NumObjCStringLiterals = 0;
634 PropParentMap = 0;
635 CurrentBody = 0;
636 DisableReplaceStmt = false;
637 objc_impl_method = false;
638
639 // Get the ID and start/end of the main file.
640 MainFileID = SM->getMainFileID();
641 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
642 MainFileStart = MainBuf->getBufferStart();
643 MainFileEnd = MainBuf->getBufferEnd();
644
David Blaikie4e4d0842012-03-11 07:00:24 +0000645 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000646}
647
648//===----------------------------------------------------------------------===//
649// Top Level Driver Code
650//===----------------------------------------------------------------------===//
651
652void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
653 if (Diags.hasErrorOccurred())
654 return;
655
656 // Two cases: either the decl could be in the main file, or it could be in a
657 // #included file. If the former, rewrite it now. If the later, check to see
658 // if we rewrote the #include/#import.
659 SourceLocation Loc = D->getLocation();
660 Loc = SM->getExpansionLoc(Loc);
661
662 // If this is for a builtin, ignore it.
663 if (Loc.isInvalid()) return;
664
665 // Look for built-in declarations that we need to refer during the rewrite.
666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
667 RewriteFunctionDecl(FD);
668 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
669 // declared in <Foundation/NSString.h>
670 if (FVD->getName() == "_NSConstantStringClassReference") {
671 ConstantStringClassReference = FVD;
672 return;
673 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000674 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
675 RewriteCategoryDecl(CD);
676 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
677 if (PD->isThisDeclarationADefinition())
678 RewriteProtocolDecl(PD);
679 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000680 // FIXME. This will not work in all situations and leaving it out
681 // is harmless.
682 // RewriteLinkageSpec(LSD);
683
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000684 // Recurse into linkage specifications
685 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
686 DIEnd = LSD->decls_end();
687 DI != DIEnd; ) {
688 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
689 if (!IFace->isThisDeclarationADefinition()) {
690 SmallVector<Decl *, 8> DG;
691 SourceLocation StartLoc = IFace->getLocStart();
692 do {
693 if (isa<ObjCInterfaceDecl>(*DI) &&
694 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
695 StartLoc == (*DI)->getLocStart())
696 DG.push_back(*DI);
697 else
698 break;
699
700 ++DI;
701 } while (DI != DIEnd);
702 RewriteForwardClassDecl(DG);
703 continue;
704 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000705 else {
706 // Keep track of all interface declarations seen.
707 ObjCInterfacesSeen.push_back(IFace);
708 ++DI;
709 continue;
710 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000711 }
712
713 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
714 if (!Proto->isThisDeclarationADefinition()) {
715 SmallVector<Decl *, 8> DG;
716 SourceLocation StartLoc = Proto->getLocStart();
717 do {
718 if (isa<ObjCProtocolDecl>(*DI) &&
719 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
720 StartLoc == (*DI)->getLocStart())
721 DG.push_back(*DI);
722 else
723 break;
724
725 ++DI;
726 } while (DI != DIEnd);
727 RewriteForwardProtocolDecl(DG);
728 continue;
729 }
730 }
731
732 HandleTopLevelSingleDecl(*DI);
733 ++DI;
734 }
735 }
736 // If we have a decl in the main file, see if we should rewrite it.
737 if (SM->isFromMainFile(Loc))
738 return HandleDeclInMainFile(D);
739}
740
741//===----------------------------------------------------------------------===//
742// Syntactic (non-AST) Rewriting Code
743//===----------------------------------------------------------------------===//
744
745void RewriteModernObjC::RewriteInclude() {
746 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
747 StringRef MainBuf = SM->getBufferData(MainFileID);
748 const char *MainBufStart = MainBuf.begin();
749 const char *MainBufEnd = MainBuf.end();
750 size_t ImportLen = strlen("import");
751
752 // Loop over the whole file, looking for includes.
753 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
754 if (*BufPtr == '#') {
755 if (++BufPtr == MainBufEnd)
756 return;
757 while (*BufPtr == ' ' || *BufPtr == '\t')
758 if (++BufPtr == MainBufEnd)
759 return;
760 if (!strncmp(BufPtr, "import", ImportLen)) {
761 // replace import with include
762 SourceLocation ImportLoc =
763 LocStart.getLocWithOffset(BufPtr-MainBufStart);
764 ReplaceText(ImportLoc, ImportLen, "include");
765 BufPtr += ImportLen;
766 }
767 }
768 }
769}
770
771static std::string getIvarAccessString(ObjCIvarDecl *OID) {
772 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
773 std::string S;
774 S = "((struct ";
775 S += ClassDecl->getIdentifier()->getName();
776 S += "_IMPL *)self)->";
777 S += OID->getName();
778 return S;
779}
780
781void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
782 ObjCImplementationDecl *IMD,
783 ObjCCategoryImplDecl *CID) {
784 static bool objcGetPropertyDefined = false;
785 static bool objcSetPropertyDefined = false;
786 SourceLocation startLoc = PID->getLocStart();
787 InsertText(startLoc, "// ");
788 const char *startBuf = SM->getCharacterData(startLoc);
789 assert((*startBuf == '@') && "bogus @synthesize location");
790 const char *semiBuf = strchr(startBuf, ';');
791 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
792 SourceLocation onePastSemiLoc =
793 startLoc.getLocWithOffset(semiBuf-startBuf+1);
794
795 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
796 return; // FIXME: is this correct?
797
798 // Generate the 'getter' function.
799 ObjCPropertyDecl *PD = PID->getPropertyDecl();
800 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
801
802 if (!OID)
803 return;
804 unsigned Attributes = PD->getPropertyAttributes();
805 if (!PD->getGetterMethodDecl()->isDefined()) {
806 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
807 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
808 ObjCPropertyDecl::OBJC_PR_copy));
809 std::string Getr;
810 if (GenGetProperty && !objcGetPropertyDefined) {
811 objcGetPropertyDefined = true;
812 // FIXME. Is this attribute correct in all cases?
813 Getr = "\nextern \"C\" __declspec(dllimport) "
814 "id objc_getProperty(id, SEL, long, bool);\n";
815 }
816 RewriteObjCMethodDecl(OID->getContainingInterface(),
817 PD->getGetterMethodDecl(), Getr);
818 Getr += "{ ";
819 // Synthesize an explicit cast to gain access to the ivar.
820 // See objc-act.c:objc_synthesize_new_getter() for details.
821 if (GenGetProperty) {
822 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
823 Getr += "typedef ";
824 const FunctionType *FPRetType = 0;
825 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
826 FPRetType);
827 Getr += " _TYPE";
828 if (FPRetType) {
829 Getr += ")"; // close the precedence "scope" for "*".
830
831 // Now, emit the argument types (if any).
832 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
833 Getr += "(";
834 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
835 if (i) Getr += ", ";
836 std::string ParamStr = FT->getArgType(i).getAsString(
837 Context->getPrintingPolicy());
838 Getr += ParamStr;
839 }
840 if (FT->isVariadic()) {
841 if (FT->getNumArgs()) Getr += ", ";
842 Getr += "...";
843 }
844 Getr += ")";
845 } else
846 Getr += "()";
847 }
848 Getr += ";\n";
849 Getr += "return (_TYPE)";
850 Getr += "objc_getProperty(self, _cmd, ";
851 RewriteIvarOffsetComputation(OID, Getr);
852 Getr += ", 1)";
853 }
854 else
855 Getr += "return " + getIvarAccessString(OID);
856 Getr += "; }";
857 InsertText(onePastSemiLoc, Getr);
858 }
859
860 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
861 return;
862
863 // Generate the 'setter' function.
864 std::string Setr;
865 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
866 ObjCPropertyDecl::OBJC_PR_copy);
867 if (GenSetProperty && !objcSetPropertyDefined) {
868 objcSetPropertyDefined = true;
869 // FIXME. Is this attribute correct in all cases?
870 Setr = "\nextern \"C\" __declspec(dllimport) "
871 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
872 }
873
874 RewriteObjCMethodDecl(OID->getContainingInterface(),
875 PD->getSetterMethodDecl(), Setr);
876 Setr += "{ ";
877 // Synthesize an explicit cast to initialize the ivar.
878 // See objc-act.c:objc_synthesize_new_setter() for details.
879 if (GenSetProperty) {
880 Setr += "objc_setProperty (self, _cmd, ";
881 RewriteIvarOffsetComputation(OID, Setr);
882 Setr += ", (id)";
883 Setr += PD->getName();
884 Setr += ", ";
885 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
886 Setr += "0, ";
887 else
888 Setr += "1, ";
889 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
890 Setr += "1)";
891 else
892 Setr += "0)";
893 }
894 else {
895 Setr += getIvarAccessString(OID) + " = ";
896 Setr += PD->getName();
897 }
898 Setr += "; }";
899 InsertText(onePastSemiLoc, Setr);
900}
901
902static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
903 std::string &typedefString) {
904 typedefString += "#ifndef _REWRITER_typedef_";
905 typedefString += ForwardDecl->getNameAsString();
906 typedefString += "\n";
907 typedefString += "#define _REWRITER_typedef_";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += "\n";
910 typedefString += "typedef struct objc_object ";
911 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000912 // typedef struct { } _objc_exc_Classname;
913 typedefString += ";\ntypedef struct {} _objc_exc_";
914 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000915 typedefString += ";\n#endif\n";
916}
917
918void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
919 const std::string &typedefString) {
920 SourceLocation startLoc = ClassDecl->getLocStart();
921 const char *startBuf = SM->getCharacterData(startLoc);
922 const char *semiPtr = strchr(startBuf, ';');
923 // Replace the @class with typedefs corresponding to the classes.
924 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
925}
926
927void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
928 std::string typedefString;
929 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
930 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
931 if (I == D.begin()) {
932 // Translate to typedef's that forward reference structs with the same name
933 // as the class. As a convenience, we include the original declaration
934 // as a comment.
935 typedefString += "// @class ";
936 typedefString += ForwardDecl->getNameAsString();
937 typedefString += ";\n";
938 }
939 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
940 }
941 DeclGroupRef::iterator I = D.begin();
942 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
943}
944
945void RewriteModernObjC::RewriteForwardClassDecl(
946 const llvm::SmallVector<Decl*, 8> &D) {
947 std::string typedefString;
948 for (unsigned i = 0; i < D.size(); i++) {
949 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
950 if (i == 0) {
951 typedefString += "// @class ";
952 typedefString += ForwardDecl->getNameAsString();
953 typedefString += ";\n";
954 }
955 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
956 }
957 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
958}
959
960void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
961 // When method is a synthesized one, such as a getter/setter there is
962 // nothing to rewrite.
963 if (Method->isImplicit())
964 return;
965 SourceLocation LocStart = Method->getLocStart();
966 SourceLocation LocEnd = Method->getLocEnd();
967
968 if (SM->getExpansionLineNumber(LocEnd) >
969 SM->getExpansionLineNumber(LocStart)) {
970 InsertText(LocStart, "#if 0\n");
971 ReplaceText(LocEnd, 1, ";\n#endif\n");
972 } else {
973 InsertText(LocStart, "// ");
974 }
975}
976
977void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
978 SourceLocation Loc = prop->getAtLoc();
979
980 ReplaceText(Loc, 0, "// ");
981 // FIXME: handle properties that are declared across multiple lines.
982}
983
984void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
985 SourceLocation LocStart = CatDecl->getLocStart();
986
987 // FIXME: handle category headers that are declared across multiple lines.
988 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000989 if (CatDecl->getIvarLBraceLoc().isValid())
990 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000991 for (ObjCCategoryDecl::ivar_iterator
992 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
993 ObjCIvarDecl *Ivar = (*I);
994 SourceLocation LocStart = Ivar->getLocStart();
995 ReplaceText(LocStart, 0, "// ");
996 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000997 if (CatDecl->getIvarRBraceLoc().isValid())
998 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
999
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001000 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1001 E = CatDecl->prop_end(); I != E; ++I)
1002 RewriteProperty(*I);
1003
1004 for (ObjCCategoryDecl::instmeth_iterator
1005 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1006 I != E; ++I)
1007 RewriteMethodDeclaration(*I);
1008 for (ObjCCategoryDecl::classmeth_iterator
1009 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1010 I != E; ++I)
1011 RewriteMethodDeclaration(*I);
1012
1013 // Lastly, comment out the @end.
1014 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1015 strlen("@end"), "/* @end */");
1016}
1017
1018void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1019 SourceLocation LocStart = PDecl->getLocStart();
1020 assert(PDecl->isThisDeclarationADefinition());
1021
1022 // FIXME: handle protocol headers that are declared across multiple lines.
1023 ReplaceText(LocStart, 0, "// ");
1024
1025 for (ObjCProtocolDecl::instmeth_iterator
1026 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1027 I != E; ++I)
1028 RewriteMethodDeclaration(*I);
1029 for (ObjCProtocolDecl::classmeth_iterator
1030 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1031 I != E; ++I)
1032 RewriteMethodDeclaration(*I);
1033
1034 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1035 E = PDecl->prop_end(); I != E; ++I)
1036 RewriteProperty(*I);
1037
1038 // Lastly, comment out the @end.
1039 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1040 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1041
1042 // Must comment out @optional/@required
1043 const char *startBuf = SM->getCharacterData(LocStart);
1044 const char *endBuf = SM->getCharacterData(LocEnd);
1045 for (const char *p = startBuf; p < endBuf; p++) {
1046 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1047 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1048 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1049
1050 }
1051 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1052 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1053 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1054
1055 }
1056 }
1057}
1058
1059void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1060 SourceLocation LocStart = (*D.begin())->getLocStart();
1061 if (LocStart.isInvalid())
1062 llvm_unreachable("Invalid SourceLocation");
1063 // FIXME: handle forward protocol that are declared across multiple lines.
1064 ReplaceText(LocStart, 0, "// ");
1065}
1066
1067void
1068RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1069 SourceLocation LocStart = DG[0]->getLocStart();
1070 if (LocStart.isInvalid())
1071 llvm_unreachable("Invalid SourceLocation");
1072 // FIXME: handle forward protocol that are declared across multiple lines.
1073 ReplaceText(LocStart, 0, "// ");
1074}
1075
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001076void
1077RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1078 SourceLocation LocStart = LSD->getExternLoc();
1079 if (LocStart.isInvalid())
1080 llvm_unreachable("Invalid extern SourceLocation");
1081
1082 ReplaceText(LocStart, 0, "// ");
1083 if (!LSD->hasBraces())
1084 return;
1085 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1086 SourceLocation LocRBrace = LSD->getRBraceLoc();
1087 if (LocRBrace.isInvalid())
1088 llvm_unreachable("Invalid rbrace SourceLocation");
1089 ReplaceText(LocRBrace, 0, "// ");
1090}
1091
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001092void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1093 const FunctionType *&FPRetType) {
1094 if (T->isObjCQualifiedIdType())
1095 ResultStr += "id";
1096 else if (T->isFunctionPointerType() ||
1097 T->isBlockPointerType()) {
1098 // needs special handling, since pointer-to-functions have special
1099 // syntax (where a decaration models use).
1100 QualType retType = T;
1101 QualType PointeeTy;
1102 if (const PointerType* PT = retType->getAs<PointerType>())
1103 PointeeTy = PT->getPointeeType();
1104 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1105 PointeeTy = BPT->getPointeeType();
1106 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1107 ResultStr += FPRetType->getResultType().getAsString(
1108 Context->getPrintingPolicy());
1109 ResultStr += "(*";
1110 }
1111 } else
1112 ResultStr += T.getAsString(Context->getPrintingPolicy());
1113}
1114
1115void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1116 ObjCMethodDecl *OMD,
1117 std::string &ResultStr) {
1118 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1119 const FunctionType *FPRetType = 0;
1120 ResultStr += "\nstatic ";
1121 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1122 ResultStr += " ";
1123
1124 // Unique method name
1125 std::string NameStr;
1126
1127 if (OMD->isInstanceMethod())
1128 NameStr += "_I_";
1129 else
1130 NameStr += "_C_";
1131
1132 NameStr += IDecl->getNameAsString();
1133 NameStr += "_";
1134
1135 if (ObjCCategoryImplDecl *CID =
1136 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1137 NameStr += CID->getNameAsString();
1138 NameStr += "_";
1139 }
1140 // Append selector names, replacing ':' with '_'
1141 {
1142 std::string selString = OMD->getSelector().getAsString();
1143 int len = selString.size();
1144 for (int i = 0; i < len; i++)
1145 if (selString[i] == ':')
1146 selString[i] = '_';
1147 NameStr += selString;
1148 }
1149 // Remember this name for metadata emission
1150 MethodInternalNames[OMD] = NameStr;
1151 ResultStr += NameStr;
1152
1153 // Rewrite arguments
1154 ResultStr += "(";
1155
1156 // invisible arguments
1157 if (OMD->isInstanceMethod()) {
1158 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1159 selfTy = Context->getPointerType(selfTy);
1160 if (!LangOpts.MicrosoftExt) {
1161 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1162 ResultStr += "struct ";
1163 }
1164 // When rewriting for Microsoft, explicitly omit the structure name.
1165 ResultStr += IDecl->getNameAsString();
1166 ResultStr += " *";
1167 }
1168 else
1169 ResultStr += Context->getObjCClassType().getAsString(
1170 Context->getPrintingPolicy());
1171
1172 ResultStr += " self, ";
1173 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1174 ResultStr += " _cmd";
1175
1176 // Method arguments.
1177 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1178 E = OMD->param_end(); PI != E; ++PI) {
1179 ParmVarDecl *PDecl = *PI;
1180 ResultStr += ", ";
1181 if (PDecl->getType()->isObjCQualifiedIdType()) {
1182 ResultStr += "id ";
1183 ResultStr += PDecl->getNameAsString();
1184 } else {
1185 std::string Name = PDecl->getNameAsString();
1186 QualType QT = PDecl->getType();
1187 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001188 (void)convertBlockPointerToFunctionPointer(QT);
1189 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001190 ResultStr += Name;
1191 }
1192 }
1193 if (OMD->isVariadic())
1194 ResultStr += ", ...";
1195 ResultStr += ") ";
1196
1197 if (FPRetType) {
1198 ResultStr += ")"; // close the precedence "scope" for "*".
1199
1200 // Now, emit the argument types (if any).
1201 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1202 ResultStr += "(";
1203 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1204 if (i) ResultStr += ", ";
1205 std::string ParamStr = FT->getArgType(i).getAsString(
1206 Context->getPrintingPolicy());
1207 ResultStr += ParamStr;
1208 }
1209 if (FT->isVariadic()) {
1210 if (FT->getNumArgs()) ResultStr += ", ";
1211 ResultStr += "...";
1212 }
1213 ResultStr += ")";
1214 } else {
1215 ResultStr += "()";
1216 }
1217 }
1218}
1219void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1220 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1221 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1222
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001223 if (IMD) {
1224 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001225 if (IMD->getIvarLBraceLoc().isValid())
1226 InsertText(IMD->getIvarLBraceLoc(), "// ");
1227 for (ObjCImplementationDecl::ivar_iterator
1228 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1229 ObjCIvarDecl *Ivar = (*I);
1230 SourceLocation LocStart = Ivar->getLocStart();
1231 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001232 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001233 if (IMD->getIvarRBraceLoc().isValid())
1234 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001235 }
1236 else
1237 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001238
1239 for (ObjCCategoryImplDecl::instmeth_iterator
1240 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1241 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1242 I != E; ++I) {
1243 std::string ResultStr;
1244 ObjCMethodDecl *OMD = *I;
1245 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1246 SourceLocation LocStart = OMD->getLocStart();
1247 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1248
1249 const char *startBuf = SM->getCharacterData(LocStart);
1250 const char *endBuf = SM->getCharacterData(LocEnd);
1251 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1252 }
1253
1254 for (ObjCCategoryImplDecl::classmeth_iterator
1255 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1256 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1257 I != E; ++I) {
1258 std::string ResultStr;
1259 ObjCMethodDecl *OMD = *I;
1260 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1261 SourceLocation LocStart = OMD->getLocStart();
1262 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1263
1264 const char *startBuf = SM->getCharacterData(LocStart);
1265 const char *endBuf = SM->getCharacterData(LocEnd);
1266 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1267 }
1268 for (ObjCCategoryImplDecl::propimpl_iterator
1269 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1270 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1271 I != E; ++I) {
1272 RewritePropertyImplDecl(*I, IMD, CID);
1273 }
1274
1275 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1276}
1277
1278void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001279 // Do not synthesize more than once.
1280 if (ObjCSynthesizedStructs.count(ClassDecl))
1281 return;
1282 // Make sure super class's are written before current class is written.
1283 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1284 while (SuperClass) {
1285 RewriteInterfaceDecl(SuperClass);
1286 SuperClass = SuperClass->getSuperClass();
1287 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001288 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001289 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001290 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001291 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001292 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1293
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001294 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001295 // Mark this typedef as having been written into its c++ equivalent.
1296 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001297
1298 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001299 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001300 RewriteProperty(*I);
1301 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001302 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001303 I != E; ++I)
1304 RewriteMethodDeclaration(*I);
1305 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001306 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001307 I != E; ++I)
1308 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001309
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001310 // Lastly, comment out the @end.
1311 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1312 "/* @end */");
1313 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001314}
1315
1316Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1317 SourceRange OldRange = PseudoOp->getSourceRange();
1318
1319 // We just magically know some things about the structure of this
1320 // expression.
1321 ObjCMessageExpr *OldMsg =
1322 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1323 PseudoOp->getNumSemanticExprs() - 1));
1324
1325 // Because the rewriter doesn't allow us to rewrite rewritten code,
1326 // we need to suppress rewriting the sub-statements.
1327 Expr *Base, *RHS;
1328 {
1329 DisableReplaceStmtScope S(*this);
1330
1331 // Rebuild the base expression if we have one.
1332 Base = 0;
1333 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1334 Base = OldMsg->getInstanceReceiver();
1335 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1336 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1337 }
1338
1339 // Rebuild the RHS.
1340 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1341 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1342 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1343 }
1344
1345 // TODO: avoid this copy.
1346 SmallVector<SourceLocation, 1> SelLocs;
1347 OldMsg->getSelectorLocs(SelLocs);
1348
1349 ObjCMessageExpr *NewMsg = 0;
1350 switch (OldMsg->getReceiverKind()) {
1351 case ObjCMessageExpr::Class:
1352 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353 OldMsg->getValueKind(),
1354 OldMsg->getLeftLoc(),
1355 OldMsg->getClassReceiverTypeInfo(),
1356 OldMsg->getSelector(),
1357 SelLocs,
1358 OldMsg->getMethodDecl(),
1359 RHS,
1360 OldMsg->getRightLoc(),
1361 OldMsg->isImplicit());
1362 break;
1363
1364 case ObjCMessageExpr::Instance:
1365 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366 OldMsg->getValueKind(),
1367 OldMsg->getLeftLoc(),
1368 Base,
1369 OldMsg->getSelector(),
1370 SelLocs,
1371 OldMsg->getMethodDecl(),
1372 RHS,
1373 OldMsg->getRightLoc(),
1374 OldMsg->isImplicit());
1375 break;
1376
1377 case ObjCMessageExpr::SuperClass:
1378 case ObjCMessageExpr::SuperInstance:
1379 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1380 OldMsg->getValueKind(),
1381 OldMsg->getLeftLoc(),
1382 OldMsg->getSuperLoc(),
1383 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1384 OldMsg->getSuperType(),
1385 OldMsg->getSelector(),
1386 SelLocs,
1387 OldMsg->getMethodDecl(),
1388 RHS,
1389 OldMsg->getRightLoc(),
1390 OldMsg->isImplicit());
1391 break;
1392 }
1393
1394 Stmt *Replacement = SynthMessageExpr(NewMsg);
1395 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1396 return Replacement;
1397}
1398
1399Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1400 SourceRange OldRange = PseudoOp->getSourceRange();
1401
1402 // We just magically know some things about the structure of this
1403 // expression.
1404 ObjCMessageExpr *OldMsg =
1405 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1406
1407 // Because the rewriter doesn't allow us to rewrite rewritten code,
1408 // we need to suppress rewriting the sub-statements.
1409 Expr *Base = 0;
1410 {
1411 DisableReplaceStmtScope S(*this);
1412
1413 // Rebuild the base expression if we have one.
1414 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1415 Base = OldMsg->getInstanceReceiver();
1416 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1417 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1418 }
1419 }
1420
1421 // Intentionally empty.
1422 SmallVector<SourceLocation, 1> SelLocs;
1423 SmallVector<Expr*, 1> Args;
1424
1425 ObjCMessageExpr *NewMsg = 0;
1426 switch (OldMsg->getReceiverKind()) {
1427 case ObjCMessageExpr::Class:
1428 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1429 OldMsg->getValueKind(),
1430 OldMsg->getLeftLoc(),
1431 OldMsg->getClassReceiverTypeInfo(),
1432 OldMsg->getSelector(),
1433 SelLocs,
1434 OldMsg->getMethodDecl(),
1435 Args,
1436 OldMsg->getRightLoc(),
1437 OldMsg->isImplicit());
1438 break;
1439
1440 case ObjCMessageExpr::Instance:
1441 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1442 OldMsg->getValueKind(),
1443 OldMsg->getLeftLoc(),
1444 Base,
1445 OldMsg->getSelector(),
1446 SelLocs,
1447 OldMsg->getMethodDecl(),
1448 Args,
1449 OldMsg->getRightLoc(),
1450 OldMsg->isImplicit());
1451 break;
1452
1453 case ObjCMessageExpr::SuperClass:
1454 case ObjCMessageExpr::SuperInstance:
1455 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1456 OldMsg->getValueKind(),
1457 OldMsg->getLeftLoc(),
1458 OldMsg->getSuperLoc(),
1459 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1460 OldMsg->getSuperType(),
1461 OldMsg->getSelector(),
1462 SelLocs,
1463 OldMsg->getMethodDecl(),
1464 Args,
1465 OldMsg->getRightLoc(),
1466 OldMsg->isImplicit());
1467 break;
1468 }
1469
1470 Stmt *Replacement = SynthMessageExpr(NewMsg);
1471 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1472 return Replacement;
1473}
1474
1475/// SynthCountByEnumWithState - To print:
1476/// ((unsigned int (*)
1477/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1478/// (void *)objc_msgSend)((id)l_collection,
1479/// sel_registerName(
1480/// "countByEnumeratingWithState:objects:count:"),
1481/// &enumState,
1482/// (id *)__rw_items, (unsigned int)16)
1483///
1484void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1485 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1486 "id *, unsigned int))(void *)objc_msgSend)";
1487 buf += "\n\t\t";
1488 buf += "((id)l_collection,\n\t\t";
1489 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1490 buf += "\n\t\t";
1491 buf += "&enumState, "
1492 "(id *)__rw_items, (unsigned int)16)";
1493}
1494
1495/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1496/// statement to exit to its outer synthesized loop.
1497///
1498Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1499 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1500 return S;
1501 // replace break with goto __break_label
1502 std::string buf;
1503
1504 SourceLocation startLoc = S->getLocStart();
1505 buf = "goto __break_label_";
1506 buf += utostr(ObjCBcLabelNo.back());
1507 ReplaceText(startLoc, strlen("break"), buf);
1508
1509 return 0;
1510}
1511
1512/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1513/// statement to continue with its inner synthesized loop.
1514///
1515Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1516 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1517 return S;
1518 // replace continue with goto __continue_label
1519 std::string buf;
1520
1521 SourceLocation startLoc = S->getLocStart();
1522 buf = "goto __continue_label_";
1523 buf += utostr(ObjCBcLabelNo.back());
1524 ReplaceText(startLoc, strlen("continue"), buf);
1525
1526 return 0;
1527}
1528
1529/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1530/// It rewrites:
1531/// for ( type elem in collection) { stmts; }
1532
1533/// Into:
1534/// {
1535/// type elem;
1536/// struct __objcFastEnumerationState enumState = { 0 };
1537/// id __rw_items[16];
1538/// id l_collection = (id)collection;
1539/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1540/// objects:__rw_items count:16];
1541/// if (limit) {
1542/// unsigned long startMutations = *enumState.mutationsPtr;
1543/// do {
1544/// unsigned long counter = 0;
1545/// do {
1546/// if (startMutations != *enumState.mutationsPtr)
1547/// objc_enumerationMutation(l_collection);
1548/// elem = (type)enumState.itemsPtr[counter++];
1549/// stmts;
1550/// __continue_label: ;
1551/// } while (counter < limit);
1552/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1553/// objects:__rw_items count:16]);
1554/// elem = nil;
1555/// __break_label: ;
1556/// }
1557/// else
1558/// elem = nil;
1559/// }
1560///
1561Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1562 SourceLocation OrigEnd) {
1563 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1564 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1565 "ObjCForCollectionStmt Statement stack mismatch");
1566 assert(!ObjCBcLabelNo.empty() &&
1567 "ObjCForCollectionStmt - Label No stack empty");
1568
1569 SourceLocation startLoc = S->getLocStart();
1570 const char *startBuf = SM->getCharacterData(startLoc);
1571 StringRef elementName;
1572 std::string elementTypeAsString;
1573 std::string buf;
1574 buf = "\n{\n\t";
1575 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1576 // type elem;
1577 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1578 QualType ElementType = cast<ValueDecl>(D)->getType();
1579 if (ElementType->isObjCQualifiedIdType() ||
1580 ElementType->isObjCQualifiedInterfaceType())
1581 // Simply use 'id' for all qualified types.
1582 elementTypeAsString = "id";
1583 else
1584 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1585 buf += elementTypeAsString;
1586 buf += " ";
1587 elementName = D->getName();
1588 buf += elementName;
1589 buf += ";\n\t";
1590 }
1591 else {
1592 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1593 elementName = DR->getDecl()->getName();
1594 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1595 if (VD->getType()->isObjCQualifiedIdType() ||
1596 VD->getType()->isObjCQualifiedInterfaceType())
1597 // Simply use 'id' for all qualified types.
1598 elementTypeAsString = "id";
1599 else
1600 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1601 }
1602
1603 // struct __objcFastEnumerationState enumState = { 0 };
1604 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1605 // id __rw_items[16];
1606 buf += "id __rw_items[16];\n\t";
1607 // id l_collection = (id)
1608 buf += "id l_collection = (id)";
1609 // Find start location of 'collection' the hard way!
1610 const char *startCollectionBuf = startBuf;
1611 startCollectionBuf += 3; // skip 'for'
1612 startCollectionBuf = strchr(startCollectionBuf, '(');
1613 startCollectionBuf++; // skip '('
1614 // find 'in' and skip it.
1615 while (*startCollectionBuf != ' ' ||
1616 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1617 (*(startCollectionBuf+3) != ' ' &&
1618 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1619 startCollectionBuf++;
1620 startCollectionBuf += 3;
1621
1622 // Replace: "for (type element in" with string constructed thus far.
1623 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1624 // Replace ')' in for '(' type elem in collection ')' with ';'
1625 SourceLocation rightParenLoc = S->getRParenLoc();
1626 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1627 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1628 buf = ";\n\t";
1629
1630 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1631 // objects:__rw_items count:16];
1632 // which is synthesized into:
1633 // unsigned int limit =
1634 // ((unsigned int (*)
1635 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1636 // (void *)objc_msgSend)((id)l_collection,
1637 // sel_registerName(
1638 // "countByEnumeratingWithState:objects:count:"),
1639 // (struct __objcFastEnumerationState *)&state,
1640 // (id *)__rw_items, (unsigned int)16);
1641 buf += "unsigned long limit =\n\t\t";
1642 SynthCountByEnumWithState(buf);
1643 buf += ";\n\t";
1644 /// if (limit) {
1645 /// unsigned long startMutations = *enumState.mutationsPtr;
1646 /// do {
1647 /// unsigned long counter = 0;
1648 /// do {
1649 /// if (startMutations != *enumState.mutationsPtr)
1650 /// objc_enumerationMutation(l_collection);
1651 /// elem = (type)enumState.itemsPtr[counter++];
1652 buf += "if (limit) {\n\t";
1653 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1654 buf += "do {\n\t\t";
1655 buf += "unsigned long counter = 0;\n\t\t";
1656 buf += "do {\n\t\t\t";
1657 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1658 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1659 buf += elementName;
1660 buf += " = (";
1661 buf += elementTypeAsString;
1662 buf += ")enumState.itemsPtr[counter++];";
1663 // Replace ')' in for '(' type elem in collection ')' with all of these.
1664 ReplaceText(lparenLoc, 1, buf);
1665
1666 /// __continue_label: ;
1667 /// } while (counter < limit);
1668 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1669 /// objects:__rw_items count:16]);
1670 /// elem = nil;
1671 /// __break_label: ;
1672 /// }
1673 /// else
1674 /// elem = nil;
1675 /// }
1676 ///
1677 buf = ";\n\t";
1678 buf += "__continue_label_";
1679 buf += utostr(ObjCBcLabelNo.back());
1680 buf += ": ;";
1681 buf += "\n\t\t";
1682 buf += "} while (counter < limit);\n\t";
1683 buf += "} while (limit = ";
1684 SynthCountByEnumWithState(buf);
1685 buf += ");\n\t";
1686 buf += elementName;
1687 buf += " = ((";
1688 buf += elementTypeAsString;
1689 buf += ")0);\n\t";
1690 buf += "__break_label_";
1691 buf += utostr(ObjCBcLabelNo.back());
1692 buf += ": ;\n\t";
1693 buf += "}\n\t";
1694 buf += "else\n\t\t";
1695 buf += elementName;
1696 buf += " = ((";
1697 buf += elementTypeAsString;
1698 buf += ")0);\n\t";
1699 buf += "}\n";
1700
1701 // Insert all these *after* the statement body.
1702 // FIXME: If this should support Obj-C++, support CXXTryStmt
1703 if (isa<CompoundStmt>(S->getBody())) {
1704 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1705 InsertText(endBodyLoc, buf);
1706 } else {
1707 /* Need to treat single statements specially. For example:
1708 *
1709 * for (A *a in b) if (stuff()) break;
1710 * for (A *a in b) xxxyy;
1711 *
1712 * The following code simply scans ahead to the semi to find the actual end.
1713 */
1714 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1715 const char *semiBuf = strchr(stmtBuf, ';');
1716 assert(semiBuf && "Can't find ';'");
1717 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1718 InsertText(endBodyLoc, buf);
1719 }
1720 Stmts.pop_back();
1721 ObjCBcLabelNo.pop_back();
1722 return 0;
1723}
1724
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001725static void Write_RethrowObject(std::string &buf) {
1726 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1727 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1728 buf += "\tid rethrow;\n";
1729 buf += "\t} _fin_force_rethow(_rethrow);";
1730}
1731
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001732/// RewriteObjCSynchronizedStmt -
1733/// This routine rewrites @synchronized(expr) stmt;
1734/// into:
1735/// objc_sync_enter(expr);
1736/// @try stmt @finally { objc_sync_exit(expr); }
1737///
1738Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1739 // Get the start location and compute the semi location.
1740 SourceLocation startLoc = S->getLocStart();
1741 const char *startBuf = SM->getCharacterData(startLoc);
1742
1743 assert((*startBuf == '@') && "bogus @synchronized location");
1744
1745 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001746 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001747
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001748 const char *lparenBuf = startBuf;
1749 while (*lparenBuf != '(') lparenBuf++;
1750 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001751
1752 buf = "; objc_sync_enter(_sync_obj);\n";
1753 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1754 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1755 buf += "\n\tid sync_exit;";
1756 buf += "\n\t} _sync_exit(_sync_obj);\n";
1757
1758 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1759 // the sync expression is typically a message expression that's already
1760 // been rewritten! (which implies the SourceLocation's are invalid).
1761 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1762 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1763 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1764 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1765
1766 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1767 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1768 assert (*LBraceLocBuf == '{');
1769 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001770
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001771 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001772 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1773 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001774
1775 buf = "} catch (id e) {_rethrow = e;}\n";
1776 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001777 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001778 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001779
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001780 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001781
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001782 return 0;
1783}
1784
1785void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1786{
1787 // Perform a bottom up traversal of all children.
1788 for (Stmt::child_range CI = S->children(); CI; ++CI)
1789 if (*CI)
1790 WarnAboutReturnGotoStmts(*CI);
1791
1792 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1793 Diags.Report(Context->getFullLoc(S->getLocStart()),
1794 TryFinallyContainsReturnDiag);
1795 }
1796 return;
1797}
1798
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001799Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001800 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001801 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001802 std::string buf;
1803
1804 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001805 if (noCatch)
1806 buf = "{ id volatile _rethrow = 0;\n";
1807 else {
1808 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1809 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001810 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001811 // Get the start location and compute the semi location.
1812 SourceLocation startLoc = S->getLocStart();
1813 const char *startBuf = SM->getCharacterData(startLoc);
1814
1815 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001816 if (finalStmt)
1817 ReplaceText(startLoc, 1, buf);
1818 else
1819 // @try -> try
1820 ReplaceText(startLoc, 1, "");
1821
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1823 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001824 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001825
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001826 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001827 bool AtRemoved = false;
1828 if (catchDecl) {
1829 QualType t = catchDecl->getType();
1830 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1831 // Should be a pointer to a class.
1832 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1833 if (IDecl) {
1834 std::string Result;
1835 startBuf = SM->getCharacterData(startLoc);
1836 assert((*startBuf == '@') && "bogus @catch location");
1837 SourceLocation rParenLoc = Catch->getRParenLoc();
1838 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1839
1840 // _objc_exc_Foo *_e as argument to catch.
1841 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1842 Result += " *_"; Result += catchDecl->getNameAsString();
1843 Result += ")";
1844 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1845 // Foo *e = (Foo *)_e;
1846 Result.clear();
1847 Result = "{ ";
1848 Result += IDecl->getNameAsString();
1849 Result += " *"; Result += catchDecl->getNameAsString();
1850 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1851 Result += "_"; Result += catchDecl->getNameAsString();
1852
1853 Result += "; ";
1854 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1855 ReplaceText(lBraceLoc, 1, Result);
1856 AtRemoved = true;
1857 }
1858 }
1859 }
1860 if (!AtRemoved)
1861 // @catch -> catch
1862 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001864 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001865 if (finalStmt) {
1866 buf.clear();
1867 if (noCatch)
1868 buf = "catch (id e) {_rethrow = e;}\n";
1869 else
1870 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1871
1872 SourceLocation startFinalLoc = finalStmt->getLocStart();
1873 ReplaceText(startFinalLoc, 8, buf);
1874 Stmt *body = finalStmt->getFinallyBody();
1875 SourceLocation startFinalBodyLoc = body->getLocStart();
1876 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001877 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001878 ReplaceText(startFinalBodyLoc, 1, buf);
1879
1880 SourceLocation endFinalBodyLoc = body->getLocEnd();
1881 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001882 // Now check for any return/continue/go statements within the @try.
1883 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001884 }
1885
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001886 return 0;
1887}
1888
1889// This can't be done with ReplaceStmt(S, ThrowExpr), since
1890// the throw expression is typically a message expression that's already
1891// been rewritten! (which implies the SourceLocation's are invalid).
1892Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1893 // Get the start location and compute the semi location.
1894 SourceLocation startLoc = S->getLocStart();
1895 const char *startBuf = SM->getCharacterData(startLoc);
1896
1897 assert((*startBuf == '@') && "bogus @throw location");
1898
1899 std::string buf;
1900 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1901 if (S->getThrowExpr())
1902 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001903 else
1904 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001905
1906 // handle "@ throw" correctly.
1907 const char *wBuf = strchr(startBuf, 'w');
1908 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1909 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1910
1911 const char *semiBuf = strchr(startBuf, ';');
1912 assert((*semiBuf == ';') && "@throw: can't find ';'");
1913 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001914 if (S->getThrowExpr())
1915 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001916 return 0;
1917}
1918
1919Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1920 // Create a new string expression.
1921 QualType StrType = Context->getPointerType(Context->CharTy);
1922 std::string StrEncoding;
1923 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1924 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1925 StringLiteral::Ascii, false,
1926 StrType, SourceLocation());
1927 ReplaceStmt(Exp, Replacement);
1928
1929 // Replace this subexpr in the parent.
1930 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1931 return Replacement;
1932}
1933
1934Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1935 if (!SelGetUidFunctionDecl)
1936 SynthSelGetUidFunctionDecl();
1937 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1938 // Create a call to sel_registerName("selName").
1939 SmallVector<Expr*, 8> SelExprs;
1940 QualType argType = Context->getPointerType(Context->CharTy);
1941 SelExprs.push_back(StringLiteral::Create(*Context,
1942 Exp->getSelector().getAsString(),
1943 StringLiteral::Ascii, false,
1944 argType, SourceLocation()));
1945 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1946 &SelExprs[0], SelExprs.size());
1947 ReplaceStmt(Exp, SelExp);
1948 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1949 return SelExp;
1950}
1951
1952CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1953 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1954 SourceLocation EndLoc) {
1955 // Get the type, we will need to reference it in a couple spots.
1956 QualType msgSendType = FD->getType();
1957
1958 // Create a reference to the objc_msgSend() declaration.
1959 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001960 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001961
1962 // Now, we cast the reference to a pointer to the objc_msgSend type.
1963 QualType pToFunc = Context->getPointerType(msgSendType);
1964 ImplicitCastExpr *ICE =
1965 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1966 DRE, 0, VK_RValue);
1967
1968 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1969
1970 CallExpr *Exp =
1971 new (Context) CallExpr(*Context, ICE, args, nargs,
1972 FT->getCallResultType(*Context),
1973 VK_RValue, EndLoc);
1974 return Exp;
1975}
1976
1977static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1978 const char *&startRef, const char *&endRef) {
1979 while (startBuf < endBuf) {
1980 if (*startBuf == '<')
1981 startRef = startBuf; // mark the start.
1982 if (*startBuf == '>') {
1983 if (startRef && *startRef == '<') {
1984 endRef = startBuf; // mark the end.
1985 return true;
1986 }
1987 return false;
1988 }
1989 startBuf++;
1990 }
1991 return false;
1992}
1993
1994static void scanToNextArgument(const char *&argRef) {
1995 int angle = 0;
1996 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1997 if (*argRef == '<')
1998 angle++;
1999 else if (*argRef == '>')
2000 angle--;
2001 argRef++;
2002 }
2003 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2004}
2005
2006bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2007 if (T->isObjCQualifiedIdType())
2008 return true;
2009 if (const PointerType *PT = T->getAs<PointerType>()) {
2010 if (PT->getPointeeType()->isObjCQualifiedIdType())
2011 return true;
2012 }
2013 if (T->isObjCObjectPointerType()) {
2014 T = T->getPointeeType();
2015 return T->isObjCQualifiedInterfaceType();
2016 }
2017 if (T->isArrayType()) {
2018 QualType ElemTy = Context->getBaseElementType(T);
2019 return needToScanForQualifiers(ElemTy);
2020 }
2021 return false;
2022}
2023
2024void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2025 QualType Type = E->getType();
2026 if (needToScanForQualifiers(Type)) {
2027 SourceLocation Loc, EndLoc;
2028
2029 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2030 Loc = ECE->getLParenLoc();
2031 EndLoc = ECE->getRParenLoc();
2032 } else {
2033 Loc = E->getLocStart();
2034 EndLoc = E->getLocEnd();
2035 }
2036 // This will defend against trying to rewrite synthesized expressions.
2037 if (Loc.isInvalid() || EndLoc.isInvalid())
2038 return;
2039
2040 const char *startBuf = SM->getCharacterData(Loc);
2041 const char *endBuf = SM->getCharacterData(EndLoc);
2042 const char *startRef = 0, *endRef = 0;
2043 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2044 // Get the locations of the startRef, endRef.
2045 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2046 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2047 // Comment out the protocol references.
2048 InsertText(LessLoc, "/*");
2049 InsertText(GreaterLoc, "*/");
2050 }
2051 }
2052}
2053
2054void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2055 SourceLocation Loc;
2056 QualType Type;
2057 const FunctionProtoType *proto = 0;
2058 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2059 Loc = VD->getLocation();
2060 Type = VD->getType();
2061 }
2062 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2063 Loc = FD->getLocation();
2064 // Check for ObjC 'id' and class types that have been adorned with protocol
2065 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2066 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2067 assert(funcType && "missing function type");
2068 proto = dyn_cast<FunctionProtoType>(funcType);
2069 if (!proto)
2070 return;
2071 Type = proto->getResultType();
2072 }
2073 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2074 Loc = FD->getLocation();
2075 Type = FD->getType();
2076 }
2077 else
2078 return;
2079
2080 if (needToScanForQualifiers(Type)) {
2081 // Since types are unique, we need to scan the buffer.
2082
2083 const char *endBuf = SM->getCharacterData(Loc);
2084 const char *startBuf = endBuf;
2085 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2086 startBuf--; // scan backward (from the decl location) for return type.
2087 const char *startRef = 0, *endRef = 0;
2088 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2089 // Get the locations of the startRef, endRef.
2090 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2091 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2092 // Comment out the protocol references.
2093 InsertText(LessLoc, "/*");
2094 InsertText(GreaterLoc, "*/");
2095 }
2096 }
2097 if (!proto)
2098 return; // most likely, was a variable
2099 // Now check arguments.
2100 const char *startBuf = SM->getCharacterData(Loc);
2101 const char *startFuncBuf = startBuf;
2102 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2103 if (needToScanForQualifiers(proto->getArgType(i))) {
2104 // Since types are unique, we need to scan the buffer.
2105
2106 const char *endBuf = startBuf;
2107 // scan forward (from the decl location) for argument types.
2108 scanToNextArgument(endBuf);
2109 const char *startRef = 0, *endRef = 0;
2110 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2111 // Get the locations of the startRef, endRef.
2112 SourceLocation LessLoc =
2113 Loc.getLocWithOffset(startRef-startFuncBuf);
2114 SourceLocation GreaterLoc =
2115 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2116 // Comment out the protocol references.
2117 InsertText(LessLoc, "/*");
2118 InsertText(GreaterLoc, "*/");
2119 }
2120 startBuf = ++endBuf;
2121 }
2122 else {
2123 // If the function name is derived from a macro expansion, then the
2124 // argument buffer will not follow the name. Need to speak with Chris.
2125 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2126 startBuf++; // scan forward (from the decl location) for argument types.
2127 startBuf++;
2128 }
2129 }
2130}
2131
2132void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2133 QualType QT = ND->getType();
2134 const Type* TypePtr = QT->getAs<Type>();
2135 if (!isa<TypeOfExprType>(TypePtr))
2136 return;
2137 while (isa<TypeOfExprType>(TypePtr)) {
2138 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2139 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2140 TypePtr = QT->getAs<Type>();
2141 }
2142 // FIXME. This will not work for multiple declarators; as in:
2143 // __typeof__(a) b,c,d;
2144 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2145 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2146 const char *startBuf = SM->getCharacterData(DeclLoc);
2147 if (ND->getInit()) {
2148 std::string Name(ND->getNameAsString());
2149 TypeAsString += " " + Name + " = ";
2150 Expr *E = ND->getInit();
2151 SourceLocation startLoc;
2152 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2153 startLoc = ECE->getLParenLoc();
2154 else
2155 startLoc = E->getLocStart();
2156 startLoc = SM->getExpansionLoc(startLoc);
2157 const char *endBuf = SM->getCharacterData(startLoc);
2158 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2159 }
2160 else {
2161 SourceLocation X = ND->getLocEnd();
2162 X = SM->getExpansionLoc(X);
2163 const char *endBuf = SM->getCharacterData(X);
2164 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2165 }
2166}
2167
2168// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2169void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2170 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2171 SmallVector<QualType, 16> ArgTys;
2172 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2173 QualType getFuncType =
2174 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2175 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2176 SourceLocation(),
2177 SourceLocation(),
2178 SelGetUidIdent, getFuncType, 0,
2179 SC_Extern,
2180 SC_None, false);
2181}
2182
2183void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2184 // declared in <objc/objc.h>
2185 if (FD->getIdentifier() &&
2186 FD->getName() == "sel_registerName") {
2187 SelGetUidFunctionDecl = FD;
2188 return;
2189 }
2190 RewriteObjCQualifiedInterfaceTypes(FD);
2191}
2192
2193void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2194 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2195 const char *argPtr = TypeString.c_str();
2196 if (!strchr(argPtr, '^')) {
2197 Str += TypeString;
2198 return;
2199 }
2200 while (*argPtr) {
2201 Str += (*argPtr == '^' ? '*' : *argPtr);
2202 argPtr++;
2203 }
2204}
2205
2206// FIXME. Consolidate this routine with RewriteBlockPointerType.
2207void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2208 ValueDecl *VD) {
2209 QualType Type = VD->getType();
2210 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2211 const char *argPtr = TypeString.c_str();
2212 int paren = 0;
2213 while (*argPtr) {
2214 switch (*argPtr) {
2215 case '(':
2216 Str += *argPtr;
2217 paren++;
2218 break;
2219 case ')':
2220 Str += *argPtr;
2221 paren--;
2222 break;
2223 case '^':
2224 Str += '*';
2225 if (paren == 1)
2226 Str += VD->getNameAsString();
2227 break;
2228 default:
2229 Str += *argPtr;
2230 break;
2231 }
2232 argPtr++;
2233 }
2234}
2235
2236
2237void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2238 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2239 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2240 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2241 if (!proto)
2242 return;
2243 QualType Type = proto->getResultType();
2244 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2245 FdStr += " ";
2246 FdStr += FD->getName();
2247 FdStr += "(";
2248 unsigned numArgs = proto->getNumArgs();
2249 for (unsigned i = 0; i < numArgs; i++) {
2250 QualType ArgType = proto->getArgType(i);
2251 RewriteBlockPointerType(FdStr, ArgType);
2252 if (i+1 < numArgs)
2253 FdStr += ", ";
2254 }
2255 FdStr += ");\n";
2256 InsertText(FunLocStart, FdStr);
2257 CurFunctionDeclToDeclareForBlock = 0;
2258}
2259
2260// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2261void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2262 if (SuperContructorFunctionDecl)
2263 return;
2264 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2265 SmallVector<QualType, 16> ArgTys;
2266 QualType argT = Context->getObjCIdType();
2267 assert(!argT.isNull() && "Can't find 'id' type");
2268 ArgTys.push_back(argT);
2269 ArgTys.push_back(argT);
2270 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2271 &ArgTys[0], ArgTys.size());
2272 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2273 SourceLocation(),
2274 SourceLocation(),
2275 msgSendIdent, msgSendType, 0,
2276 SC_Extern,
2277 SC_None, false);
2278}
2279
2280// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2281void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2282 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2283 SmallVector<QualType, 16> ArgTys;
2284 QualType argT = Context->getObjCIdType();
2285 assert(!argT.isNull() && "Can't find 'id' type");
2286 ArgTys.push_back(argT);
2287 argT = Context->getObjCSelType();
2288 assert(!argT.isNull() && "Can't find 'SEL' type");
2289 ArgTys.push_back(argT);
2290 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2291 &ArgTys[0], ArgTys.size(),
2292 true /*isVariadic*/);
2293 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2294 SourceLocation(),
2295 SourceLocation(),
2296 msgSendIdent, msgSendType, 0,
2297 SC_Extern,
2298 SC_None, false);
2299}
2300
2301// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2302void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2303 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2304 SmallVector<QualType, 16> ArgTys;
2305 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2306 SourceLocation(), SourceLocation(),
2307 &Context->Idents.get("objc_super"));
2308 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2309 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2310 ArgTys.push_back(argT);
2311 argT = Context->getObjCSelType();
2312 assert(!argT.isNull() && "Can't find 'SEL' type");
2313 ArgTys.push_back(argT);
2314 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2315 &ArgTys[0], ArgTys.size(),
2316 true /*isVariadic*/);
2317 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2318 SourceLocation(),
2319 SourceLocation(),
2320 msgSendIdent, msgSendType, 0,
2321 SC_Extern,
2322 SC_None, false);
2323}
2324
2325// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2326void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2327 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2328 SmallVector<QualType, 16> ArgTys;
2329 QualType argT = Context->getObjCIdType();
2330 assert(!argT.isNull() && "Can't find 'id' type");
2331 ArgTys.push_back(argT);
2332 argT = Context->getObjCSelType();
2333 assert(!argT.isNull() && "Can't find 'SEL' type");
2334 ArgTys.push_back(argT);
2335 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2336 &ArgTys[0], ArgTys.size(),
2337 true /*isVariadic*/);
2338 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2339 SourceLocation(),
2340 SourceLocation(),
2341 msgSendIdent, msgSendType, 0,
2342 SC_Extern,
2343 SC_None, false);
2344}
2345
2346// SynthMsgSendSuperStretFunctionDecl -
2347// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2348void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2349 IdentifierInfo *msgSendIdent =
2350 &Context->Idents.get("objc_msgSendSuper_stret");
2351 SmallVector<QualType, 16> ArgTys;
2352 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2353 SourceLocation(), SourceLocation(),
2354 &Context->Idents.get("objc_super"));
2355 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2356 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2357 ArgTys.push_back(argT);
2358 argT = Context->getObjCSelType();
2359 assert(!argT.isNull() && "Can't find 'SEL' type");
2360 ArgTys.push_back(argT);
2361 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2362 &ArgTys[0], ArgTys.size(),
2363 true /*isVariadic*/);
2364 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2365 SourceLocation(),
2366 SourceLocation(),
2367 msgSendIdent, msgSendType, 0,
2368 SC_Extern,
2369 SC_None, false);
2370}
2371
2372// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2373void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2374 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2375 SmallVector<QualType, 16> ArgTys;
2376 QualType argT = Context->getObjCIdType();
2377 assert(!argT.isNull() && "Can't find 'id' type");
2378 ArgTys.push_back(argT);
2379 argT = Context->getObjCSelType();
2380 assert(!argT.isNull() && "Can't find 'SEL' type");
2381 ArgTys.push_back(argT);
2382 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2383 &ArgTys[0], ArgTys.size(),
2384 true /*isVariadic*/);
2385 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2386 SourceLocation(),
2387 SourceLocation(),
2388 msgSendIdent, msgSendType, 0,
2389 SC_Extern,
2390 SC_None, false);
2391}
2392
2393// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2394void RewriteModernObjC::SynthGetClassFunctionDecl() {
2395 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2396 SmallVector<QualType, 16> ArgTys;
2397 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2398 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2399 &ArgTys[0], ArgTys.size());
2400 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2401 SourceLocation(),
2402 SourceLocation(),
2403 getClassIdent, getClassType, 0,
2404 SC_Extern,
2405 SC_None, false);
2406}
2407
2408// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2409void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2410 IdentifierInfo *getSuperClassIdent =
2411 &Context->Idents.get("class_getSuperclass");
2412 SmallVector<QualType, 16> ArgTys;
2413 ArgTys.push_back(Context->getObjCClassType());
2414 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2415 &ArgTys[0], ArgTys.size());
2416 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2417 SourceLocation(),
2418 SourceLocation(),
2419 getSuperClassIdent,
2420 getClassType, 0,
2421 SC_Extern,
2422 SC_None,
2423 false);
2424}
2425
2426// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2427void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2428 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2429 SmallVector<QualType, 16> ArgTys;
2430 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2431 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2432 &ArgTys[0], ArgTys.size());
2433 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2434 SourceLocation(),
2435 SourceLocation(),
2436 getClassIdent, getClassType, 0,
2437 SC_Extern,
2438 SC_None, false);
2439}
2440
2441Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2442 QualType strType = getConstantStringStructType();
2443
2444 std::string S = "__NSConstantStringImpl_";
2445
2446 std::string tmpName = InFileName;
2447 unsigned i;
2448 for (i=0; i < tmpName.length(); i++) {
2449 char c = tmpName.at(i);
2450 // replace any non alphanumeric characters with '_'.
2451 if (!isalpha(c) && (c < '0' || c > '9'))
2452 tmpName[i] = '_';
2453 }
2454 S += tmpName;
2455 S += "_";
2456 S += utostr(NumObjCStringLiterals++);
2457
2458 Preamble += "static __NSConstantStringImpl " + S;
2459 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2460 Preamble += "0x000007c8,"; // utf8_str
2461 // The pretty printer for StringLiteral handles escape characters properly.
2462 std::string prettyBufS;
2463 llvm::raw_string_ostream prettyBuf(prettyBufS);
2464 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2465 PrintingPolicy(LangOpts));
2466 Preamble += prettyBuf.str();
2467 Preamble += ",";
2468 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2469
2470 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2471 SourceLocation(), &Context->Idents.get(S),
2472 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002473 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002474 SourceLocation());
2475 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2476 Context->getPointerType(DRE->getType()),
2477 VK_RValue, OK_Ordinary,
2478 SourceLocation());
2479 // cast to NSConstantString *
2480 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2481 CK_CPointerToObjCPointerCast, Unop);
2482 ReplaceStmt(Exp, cast);
2483 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2484 return cast;
2485}
2486
Fariborz Jahanian55947042012-03-27 20:17:30 +00002487Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2488 unsigned IntSize =
2489 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2490
2491 Expr *FlagExp = IntegerLiteral::Create(*Context,
2492 llvm::APInt(IntSize, Exp->getValue()),
2493 Context->IntTy, Exp->getLocation());
2494 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2495 CK_BitCast, FlagExp);
2496 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2497 cast);
2498 ReplaceStmt(Exp, PE);
2499 return PE;
2500}
2501
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002502Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2503 // synthesize declaration of helper functions needed in this routine.
2504 if (!SelGetUidFunctionDecl)
2505 SynthSelGetUidFunctionDecl();
2506 // use objc_msgSend() for all.
2507 if (!MsgSendFunctionDecl)
2508 SynthMsgSendFunctionDecl();
2509 if (!GetClassFunctionDecl)
2510 SynthGetClassFunctionDecl();
2511
2512 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2513 SourceLocation StartLoc = Exp->getLocStart();
2514 SourceLocation EndLoc = Exp->getLocEnd();
2515
2516 // Synthesize a call to objc_msgSend().
2517 SmallVector<Expr*, 4> MsgExprs;
2518 SmallVector<Expr*, 4> ClsExprs;
2519 QualType argType = Context->getPointerType(Context->CharTy);
2520 QualType expType = Exp->getType();
2521
2522 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2523 ObjCInterfaceDecl *Class =
2524 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2525
2526 IdentifierInfo *clsName = Class->getIdentifier();
2527 ClsExprs.push_back(StringLiteral::Create(*Context,
2528 clsName->getName(),
2529 StringLiteral::Ascii, false,
2530 argType, SourceLocation()));
2531 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2532 &ClsExprs[0],
2533 ClsExprs.size(),
2534 StartLoc, EndLoc);
2535 MsgExprs.push_back(Cls);
2536
2537 // Create a call to sel_registerName("numberWithBool:"), etc.
2538 // it will be the 2nd argument.
2539 SmallVector<Expr*, 4> SelExprs;
2540 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2541 SelExprs.push_back(StringLiteral::Create(*Context,
2542 NumericMethod->getSelector().getAsString(),
2543 StringLiteral::Ascii, false,
2544 argType, SourceLocation()));
2545 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2546 &SelExprs[0], SelExprs.size(),
2547 StartLoc, EndLoc);
2548 MsgExprs.push_back(SelExp);
2549
2550 // User provided numeric literal is the 3rd, and last, argument.
2551 Expr *userExpr = Exp->getNumber();
2552 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2553 QualType type = ICE->getType();
2554 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2555 CastKind CK = CK_BitCast;
2556 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2557 CK = CK_IntegralToBoolean;
2558 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2559 }
2560 MsgExprs.push_back(userExpr);
2561
2562 SmallVector<QualType, 4> ArgTypes;
2563 ArgTypes.push_back(Context->getObjCIdType());
2564 ArgTypes.push_back(Context->getObjCSelType());
2565 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2566 E = NumericMethod->param_end(); PI != E; ++PI)
2567 ArgTypes.push_back((*PI)->getType());
2568
2569 QualType returnType = Exp->getType();
2570 // Get the type, we will need to reference it in a couple spots.
2571 QualType msgSendType = MsgSendFlavor->getType();
2572
2573 // Create a reference to the objc_msgSend() declaration.
2574 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2575 VK_LValue, SourceLocation());
2576
2577 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2578 Context->getPointerType(Context->VoidTy),
2579 CK_BitCast, DRE);
2580
2581 // Now do the "normal" pointer to function cast.
2582 QualType castType =
2583 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2584 NumericMethod->isVariadic());
2585 castType = Context->getPointerType(castType);
2586 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2587 cast);
2588
2589 // Don't forget the parens to enforce the proper binding.
2590 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2591
2592 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2593 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2594 MsgExprs.size(),
2595 FT->getResultType(), VK_RValue,
2596 EndLoc);
2597 ReplaceStmt(Exp, CE);
2598 return CE;
2599}
2600
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002601Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2602 // synthesize declaration of helper functions needed in this routine.
2603 if (!SelGetUidFunctionDecl)
2604 SynthSelGetUidFunctionDecl();
2605 // use objc_msgSend() for all.
2606 if (!MsgSendFunctionDecl)
2607 SynthMsgSendFunctionDecl();
2608 if (!GetClassFunctionDecl)
2609 SynthGetClassFunctionDecl();
2610
2611 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2612 SourceLocation StartLoc = Exp->getLocStart();
2613 SourceLocation EndLoc = Exp->getLocEnd();
2614
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002615 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002616 QualType IntQT = Context->IntTy;
2617 QualType NSArrayFType =
2618 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002619 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002620 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2621 DeclRefExpr *NSArrayDRE =
2622 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2623 SourceLocation());
2624
2625 SmallVector<Expr*, 16> InitExprs;
2626 unsigned NumElements = Exp->getNumElements();
2627 unsigned UnsignedIntSize =
2628 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2629 Expr *count = IntegerLiteral::Create(*Context,
2630 llvm::APInt(UnsignedIntSize, NumElements),
2631 Context->UnsignedIntTy, SourceLocation());
2632 InitExprs.push_back(count);
2633 for (unsigned i = 0; i < NumElements; i++)
2634 InitExprs.push_back(Exp->getElement(i));
2635 Expr *NSArrayCallExpr =
2636 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2637 NSArrayFType, VK_LValue, SourceLocation());
2638
2639 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2640 SourceLocation(),
2641 &Context->Idents.get("arr"),
2642 Context->getPointerType(Context->VoidPtrTy), 0,
2643 /*BitWidth=*/0, /*Mutable=*/true,
2644 /*HasInit=*/false);
2645 MemberExpr *ArrayLiteralME =
2646 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2647 SourceLocation(),
2648 ARRFD->getType(), VK_LValue,
2649 OK_Ordinary);
2650 QualType ConstIdT = Context->getObjCIdType().withConst();
2651 CStyleCastExpr * ArrayLiteralObjects =
2652 NoTypeInfoCStyleCastExpr(Context,
2653 Context->getPointerType(ConstIdT),
2654 CK_BitCast,
2655 ArrayLiteralME);
2656
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002657 // Synthesize a call to objc_msgSend().
2658 SmallVector<Expr*, 32> MsgExprs;
2659 SmallVector<Expr*, 4> ClsExprs;
2660 QualType argType = Context->getPointerType(Context->CharTy);
2661 QualType expType = Exp->getType();
2662
2663 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2664 ObjCInterfaceDecl *Class =
2665 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2666
2667 IdentifierInfo *clsName = Class->getIdentifier();
2668 ClsExprs.push_back(StringLiteral::Create(*Context,
2669 clsName->getName(),
2670 StringLiteral::Ascii, false,
2671 argType, SourceLocation()));
2672 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2673 &ClsExprs[0],
2674 ClsExprs.size(),
2675 StartLoc, EndLoc);
2676 MsgExprs.push_back(Cls);
2677
2678 // Create a call to sel_registerName("arrayWithObjects:count:").
2679 // it will be the 2nd argument.
2680 SmallVector<Expr*, 4> SelExprs;
2681 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2682 SelExprs.push_back(StringLiteral::Create(*Context,
2683 ArrayMethod->getSelector().getAsString(),
2684 StringLiteral::Ascii, false,
2685 argType, SourceLocation()));
2686 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2687 &SelExprs[0], SelExprs.size(),
2688 StartLoc, EndLoc);
2689 MsgExprs.push_back(SelExp);
2690
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002691 // (const id [])objects
2692 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002693
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002694 // (NSUInteger)cnt
2695 Expr *cnt = IntegerLiteral::Create(*Context,
2696 llvm::APInt(UnsignedIntSize, NumElements),
2697 Context->UnsignedIntTy, SourceLocation());
2698 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002699
2700
2701 SmallVector<QualType, 4> ArgTypes;
2702 ArgTypes.push_back(Context->getObjCIdType());
2703 ArgTypes.push_back(Context->getObjCSelType());
2704 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2705 E = ArrayMethod->param_end(); PI != E; ++PI)
2706 ArgTypes.push_back((*PI)->getType());
2707
2708 QualType returnType = Exp->getType();
2709 // Get the type, we will need to reference it in a couple spots.
2710 QualType msgSendType = MsgSendFlavor->getType();
2711
2712 // Create a reference to the objc_msgSend() declaration.
2713 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2714 VK_LValue, SourceLocation());
2715
2716 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2717 Context->getPointerType(Context->VoidTy),
2718 CK_BitCast, DRE);
2719
2720 // Now do the "normal" pointer to function cast.
2721 QualType castType =
2722 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2723 ArrayMethod->isVariadic());
2724 castType = Context->getPointerType(castType);
2725 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2726 cast);
2727
2728 // Don't forget the parens to enforce the proper binding.
2729 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2730
2731 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2732 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2733 MsgExprs.size(),
2734 FT->getResultType(), VK_RValue,
2735 EndLoc);
2736 ReplaceStmt(Exp, CE);
2737 return CE;
2738}
2739
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002740Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2741 // synthesize declaration of helper functions needed in this routine.
2742 if (!SelGetUidFunctionDecl)
2743 SynthSelGetUidFunctionDecl();
2744 // use objc_msgSend() for all.
2745 if (!MsgSendFunctionDecl)
2746 SynthMsgSendFunctionDecl();
2747 if (!GetClassFunctionDecl)
2748 SynthGetClassFunctionDecl();
2749
2750 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2751 SourceLocation StartLoc = Exp->getLocStart();
2752 SourceLocation EndLoc = Exp->getLocEnd();
2753
2754 // Build the expression: __NSContainer_literal(int, ...).arr
2755 QualType IntQT = Context->IntTy;
2756 QualType NSDictFType =
2757 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2758 std::string NSDictFName("__NSContainer_literal");
2759 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2760 DeclRefExpr *NSDictDRE =
2761 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2762 SourceLocation());
2763
2764 SmallVector<Expr*, 16> KeyExprs;
2765 SmallVector<Expr*, 16> ValueExprs;
2766
2767 unsigned NumElements = Exp->getNumElements();
2768 unsigned UnsignedIntSize =
2769 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2770 Expr *count = IntegerLiteral::Create(*Context,
2771 llvm::APInt(UnsignedIntSize, NumElements),
2772 Context->UnsignedIntTy, SourceLocation());
2773 KeyExprs.push_back(count);
2774 ValueExprs.push_back(count);
2775 for (unsigned i = 0; i < NumElements; i++) {
2776 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2777 KeyExprs.push_back(Element.Key);
2778 ValueExprs.push_back(Element.Value);
2779 }
2780
2781 // (const id [])objects
2782 Expr *NSValueCallExpr =
2783 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2784 NSDictFType, VK_LValue, SourceLocation());
2785
2786 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2787 SourceLocation(),
2788 &Context->Idents.get("arr"),
2789 Context->getPointerType(Context->VoidPtrTy), 0,
2790 /*BitWidth=*/0, /*Mutable=*/true,
2791 /*HasInit=*/false);
2792 MemberExpr *DictLiteralValueME =
2793 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2794 SourceLocation(),
2795 ARRFD->getType(), VK_LValue,
2796 OK_Ordinary);
2797 QualType ConstIdT = Context->getObjCIdType().withConst();
2798 CStyleCastExpr * DictValueObjects =
2799 NoTypeInfoCStyleCastExpr(Context,
2800 Context->getPointerType(ConstIdT),
2801 CK_BitCast,
2802 DictLiteralValueME);
2803 // (const id <NSCopying> [])keys
2804 Expr *NSKeyCallExpr =
2805 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2806 NSDictFType, VK_LValue, SourceLocation());
2807
2808 MemberExpr *DictLiteralKeyME =
2809 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2810 SourceLocation(),
2811 ARRFD->getType(), VK_LValue,
2812 OK_Ordinary);
2813
2814 CStyleCastExpr * DictKeyObjects =
2815 NoTypeInfoCStyleCastExpr(Context,
2816 Context->getPointerType(ConstIdT),
2817 CK_BitCast,
2818 DictLiteralKeyME);
2819
2820
2821
2822 // Synthesize a call to objc_msgSend().
2823 SmallVector<Expr*, 32> MsgExprs;
2824 SmallVector<Expr*, 4> ClsExprs;
2825 QualType argType = Context->getPointerType(Context->CharTy);
2826 QualType expType = Exp->getType();
2827
2828 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2829 ObjCInterfaceDecl *Class =
2830 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2831
2832 IdentifierInfo *clsName = Class->getIdentifier();
2833 ClsExprs.push_back(StringLiteral::Create(*Context,
2834 clsName->getName(),
2835 StringLiteral::Ascii, false,
2836 argType, SourceLocation()));
2837 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2838 &ClsExprs[0],
2839 ClsExprs.size(),
2840 StartLoc, EndLoc);
2841 MsgExprs.push_back(Cls);
2842
2843 // Create a call to sel_registerName("arrayWithObjects:count:").
2844 // it will be the 2nd argument.
2845 SmallVector<Expr*, 4> SelExprs;
2846 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2847 SelExprs.push_back(StringLiteral::Create(*Context,
2848 DictMethod->getSelector().getAsString(),
2849 StringLiteral::Ascii, false,
2850 argType, SourceLocation()));
2851 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2852 &SelExprs[0], SelExprs.size(),
2853 StartLoc, EndLoc);
2854 MsgExprs.push_back(SelExp);
2855
2856 // (const id [])objects
2857 MsgExprs.push_back(DictValueObjects);
2858
2859 // (const id <NSCopying> [])keys
2860 MsgExprs.push_back(DictKeyObjects);
2861
2862 // (NSUInteger)cnt
2863 Expr *cnt = IntegerLiteral::Create(*Context,
2864 llvm::APInt(UnsignedIntSize, NumElements),
2865 Context->UnsignedIntTy, SourceLocation());
2866 MsgExprs.push_back(cnt);
2867
2868
2869 SmallVector<QualType, 8> ArgTypes;
2870 ArgTypes.push_back(Context->getObjCIdType());
2871 ArgTypes.push_back(Context->getObjCSelType());
2872 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2873 E = DictMethod->param_end(); PI != E; ++PI) {
2874 QualType T = (*PI)->getType();
2875 if (const PointerType* PT = T->getAs<PointerType>()) {
2876 QualType PointeeTy = PT->getPointeeType();
2877 convertToUnqualifiedObjCType(PointeeTy);
2878 T = Context->getPointerType(PointeeTy);
2879 }
2880 ArgTypes.push_back(T);
2881 }
2882
2883 QualType returnType = Exp->getType();
2884 // Get the type, we will need to reference it in a couple spots.
2885 QualType msgSendType = MsgSendFlavor->getType();
2886
2887 // Create a reference to the objc_msgSend() declaration.
2888 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2889 VK_LValue, SourceLocation());
2890
2891 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2892 Context->getPointerType(Context->VoidTy),
2893 CK_BitCast, DRE);
2894
2895 // Now do the "normal" pointer to function cast.
2896 QualType castType =
2897 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2898 DictMethod->isVariadic());
2899 castType = Context->getPointerType(castType);
2900 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2901 cast);
2902
2903 // Don't forget the parens to enforce the proper binding.
2904 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2905
2906 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2907 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2908 MsgExprs.size(),
2909 FT->getResultType(), VK_RValue,
2910 EndLoc);
2911 ReplaceStmt(Exp, CE);
2912 return CE;
2913}
2914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002915// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2916QualType RewriteModernObjC::getSuperStructType() {
2917 if (!SuperStructDecl) {
2918 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2919 SourceLocation(), SourceLocation(),
2920 &Context->Idents.get("objc_super"));
2921 QualType FieldTypes[2];
2922
2923 // struct objc_object *receiver;
2924 FieldTypes[0] = Context->getObjCIdType();
2925 // struct objc_class *super;
2926 FieldTypes[1] = Context->getObjCClassType();
2927
2928 // Create fields
2929 for (unsigned i = 0; i < 2; ++i) {
2930 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2931 SourceLocation(),
2932 SourceLocation(), 0,
2933 FieldTypes[i], 0,
2934 /*BitWidth=*/0,
2935 /*Mutable=*/false,
2936 /*HasInit=*/false));
2937 }
2938
2939 SuperStructDecl->completeDefinition();
2940 }
2941 return Context->getTagDeclType(SuperStructDecl);
2942}
2943
2944QualType RewriteModernObjC::getConstantStringStructType() {
2945 if (!ConstantStringDecl) {
2946 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2947 SourceLocation(), SourceLocation(),
2948 &Context->Idents.get("__NSConstantStringImpl"));
2949 QualType FieldTypes[4];
2950
2951 // struct objc_object *receiver;
2952 FieldTypes[0] = Context->getObjCIdType();
2953 // int flags;
2954 FieldTypes[1] = Context->IntTy;
2955 // char *str;
2956 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2957 // long length;
2958 FieldTypes[3] = Context->LongTy;
2959
2960 // Create fields
2961 for (unsigned i = 0; i < 4; ++i) {
2962 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2963 ConstantStringDecl,
2964 SourceLocation(),
2965 SourceLocation(), 0,
2966 FieldTypes[i], 0,
2967 /*BitWidth=*/0,
2968 /*Mutable=*/true,
2969 /*HasInit=*/false));
2970 }
2971
2972 ConstantStringDecl->completeDefinition();
2973 }
2974 return Context->getTagDeclType(ConstantStringDecl);
2975}
2976
2977Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2978 SourceLocation StartLoc,
2979 SourceLocation EndLoc) {
2980 if (!SelGetUidFunctionDecl)
2981 SynthSelGetUidFunctionDecl();
2982 if (!MsgSendFunctionDecl)
2983 SynthMsgSendFunctionDecl();
2984 if (!MsgSendSuperFunctionDecl)
2985 SynthMsgSendSuperFunctionDecl();
2986 if (!MsgSendStretFunctionDecl)
2987 SynthMsgSendStretFunctionDecl();
2988 if (!MsgSendSuperStretFunctionDecl)
2989 SynthMsgSendSuperStretFunctionDecl();
2990 if (!MsgSendFpretFunctionDecl)
2991 SynthMsgSendFpretFunctionDecl();
2992 if (!GetClassFunctionDecl)
2993 SynthGetClassFunctionDecl();
2994 if (!GetSuperClassFunctionDecl)
2995 SynthGetSuperClassFunctionDecl();
2996 if (!GetMetaClassFunctionDecl)
2997 SynthGetMetaClassFunctionDecl();
2998
2999 // default to objc_msgSend().
3000 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3001 // May need to use objc_msgSend_stret() as well.
3002 FunctionDecl *MsgSendStretFlavor = 0;
3003 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3004 QualType resultType = mDecl->getResultType();
3005 if (resultType->isRecordType())
3006 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3007 else if (resultType->isRealFloatingType())
3008 MsgSendFlavor = MsgSendFpretFunctionDecl;
3009 }
3010
3011 // Synthesize a call to objc_msgSend().
3012 SmallVector<Expr*, 8> MsgExprs;
3013 switch (Exp->getReceiverKind()) {
3014 case ObjCMessageExpr::SuperClass: {
3015 MsgSendFlavor = MsgSendSuperFunctionDecl;
3016 if (MsgSendStretFlavor)
3017 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3018 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3019
3020 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3021
3022 SmallVector<Expr*, 4> InitExprs;
3023
3024 // set the receiver to self, the first argument to all methods.
3025 InitExprs.push_back(
3026 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3027 CK_BitCast,
3028 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003029 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003030 Context->getObjCIdType(),
3031 VK_RValue,
3032 SourceLocation()))
3033 ); // set the 'receiver'.
3034
3035 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3036 SmallVector<Expr*, 8> ClsExprs;
3037 QualType argType = Context->getPointerType(Context->CharTy);
3038 ClsExprs.push_back(StringLiteral::Create(*Context,
3039 ClassDecl->getIdentifier()->getName(),
3040 StringLiteral::Ascii, false,
3041 argType, SourceLocation()));
3042 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3043 &ClsExprs[0],
3044 ClsExprs.size(),
3045 StartLoc,
3046 EndLoc);
3047 // (Class)objc_getClass("CurrentClass")
3048 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3049 Context->getObjCClassType(),
3050 CK_BitCast, Cls);
3051 ClsExprs.clear();
3052 ClsExprs.push_back(ArgExpr);
3053 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3054 &ClsExprs[0], ClsExprs.size(),
3055 StartLoc, EndLoc);
3056
3057 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3058 // To turn off a warning, type-cast to 'id'
3059 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3060 NoTypeInfoCStyleCastExpr(Context,
3061 Context->getObjCIdType(),
3062 CK_BitCast, Cls));
3063 // struct objc_super
3064 QualType superType = getSuperStructType();
3065 Expr *SuperRep;
3066
3067 if (LangOpts.MicrosoftExt) {
3068 SynthSuperContructorFunctionDecl();
3069 // Simulate a contructor call...
3070 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003071 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003072 SourceLocation());
3073 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3074 InitExprs.size(),
3075 superType, VK_LValue,
3076 SourceLocation());
3077 // The code for super is a little tricky to prevent collision with
3078 // the structure definition in the header. The rewriter has it's own
3079 // internal definition (__rw_objc_super) that is uses. This is why
3080 // we need the cast below. For example:
3081 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3082 //
3083 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3084 Context->getPointerType(SuperRep->getType()),
3085 VK_RValue, OK_Ordinary,
3086 SourceLocation());
3087 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3088 Context->getPointerType(superType),
3089 CK_BitCast, SuperRep);
3090 } else {
3091 // (struct objc_super) { <exprs from above> }
3092 InitListExpr *ILE =
3093 new (Context) InitListExpr(*Context, SourceLocation(),
3094 &InitExprs[0], InitExprs.size(),
3095 SourceLocation());
3096 TypeSourceInfo *superTInfo
3097 = Context->getTrivialTypeSourceInfo(superType);
3098 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3099 superType, VK_LValue,
3100 ILE, false);
3101 // struct objc_super *
3102 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3103 Context->getPointerType(SuperRep->getType()),
3104 VK_RValue, OK_Ordinary,
3105 SourceLocation());
3106 }
3107 MsgExprs.push_back(SuperRep);
3108 break;
3109 }
3110
3111 case ObjCMessageExpr::Class: {
3112 SmallVector<Expr*, 8> ClsExprs;
3113 QualType argType = Context->getPointerType(Context->CharTy);
3114 ObjCInterfaceDecl *Class
3115 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3116 IdentifierInfo *clsName = Class->getIdentifier();
3117 ClsExprs.push_back(StringLiteral::Create(*Context,
3118 clsName->getName(),
3119 StringLiteral::Ascii, false,
3120 argType, SourceLocation()));
3121 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3122 &ClsExprs[0],
3123 ClsExprs.size(),
3124 StartLoc, EndLoc);
3125 MsgExprs.push_back(Cls);
3126 break;
3127 }
3128
3129 case ObjCMessageExpr::SuperInstance:{
3130 MsgSendFlavor = MsgSendSuperFunctionDecl;
3131 if (MsgSendStretFlavor)
3132 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3133 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3134 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3135 SmallVector<Expr*, 4> InitExprs;
3136
3137 InitExprs.push_back(
3138 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3139 CK_BitCast,
3140 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003141 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003142 Context->getObjCIdType(),
3143 VK_RValue, SourceLocation()))
3144 ); // set the 'receiver'.
3145
3146 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3147 SmallVector<Expr*, 8> ClsExprs;
3148 QualType argType = Context->getPointerType(Context->CharTy);
3149 ClsExprs.push_back(StringLiteral::Create(*Context,
3150 ClassDecl->getIdentifier()->getName(),
3151 StringLiteral::Ascii, false, argType,
3152 SourceLocation()));
3153 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3154 &ClsExprs[0],
3155 ClsExprs.size(),
3156 StartLoc, EndLoc);
3157 // (Class)objc_getClass("CurrentClass")
3158 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3159 Context->getObjCClassType(),
3160 CK_BitCast, Cls);
3161 ClsExprs.clear();
3162 ClsExprs.push_back(ArgExpr);
3163 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3164 &ClsExprs[0], ClsExprs.size(),
3165 StartLoc, EndLoc);
3166
3167 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3168 // To turn off a warning, type-cast to 'id'
3169 InitExprs.push_back(
3170 // set 'super class', using class_getSuperclass().
3171 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3172 CK_BitCast, Cls));
3173 // struct objc_super
3174 QualType superType = getSuperStructType();
3175 Expr *SuperRep;
3176
3177 if (LangOpts.MicrosoftExt) {
3178 SynthSuperContructorFunctionDecl();
3179 // Simulate a contructor call...
3180 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003181 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003182 SourceLocation());
3183 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3184 InitExprs.size(),
3185 superType, VK_LValue, SourceLocation());
3186 // The code for super is a little tricky to prevent collision with
3187 // the structure definition in the header. The rewriter has it's own
3188 // internal definition (__rw_objc_super) that is uses. This is why
3189 // we need the cast below. For example:
3190 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3191 //
3192 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3193 Context->getPointerType(SuperRep->getType()),
3194 VK_RValue, OK_Ordinary,
3195 SourceLocation());
3196 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3197 Context->getPointerType(superType),
3198 CK_BitCast, SuperRep);
3199 } else {
3200 // (struct objc_super) { <exprs from above> }
3201 InitListExpr *ILE =
3202 new (Context) InitListExpr(*Context, SourceLocation(),
3203 &InitExprs[0], InitExprs.size(),
3204 SourceLocation());
3205 TypeSourceInfo *superTInfo
3206 = Context->getTrivialTypeSourceInfo(superType);
3207 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3208 superType, VK_RValue, ILE,
3209 false);
3210 }
3211 MsgExprs.push_back(SuperRep);
3212 break;
3213 }
3214
3215 case ObjCMessageExpr::Instance: {
3216 // Remove all type-casts because it may contain objc-style types; e.g.
3217 // Foo<Proto> *.
3218 Expr *recExpr = Exp->getInstanceReceiver();
3219 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3220 recExpr = CE->getSubExpr();
3221 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3222 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3223 ? CK_BlockPointerToObjCPointerCast
3224 : CK_CPointerToObjCPointerCast;
3225
3226 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3227 CK, recExpr);
3228 MsgExprs.push_back(recExpr);
3229 break;
3230 }
3231 }
3232
3233 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3234 SmallVector<Expr*, 8> SelExprs;
3235 QualType argType = Context->getPointerType(Context->CharTy);
3236 SelExprs.push_back(StringLiteral::Create(*Context,
3237 Exp->getSelector().getAsString(),
3238 StringLiteral::Ascii, false,
3239 argType, SourceLocation()));
3240 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3241 &SelExprs[0], SelExprs.size(),
3242 StartLoc,
3243 EndLoc);
3244 MsgExprs.push_back(SelExp);
3245
3246 // Now push any user supplied arguments.
3247 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3248 Expr *userExpr = Exp->getArg(i);
3249 // Make all implicit casts explicit...ICE comes in handy:-)
3250 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3251 // Reuse the ICE type, it is exactly what the doctor ordered.
3252 QualType type = ICE->getType();
3253 if (needToScanForQualifiers(type))
3254 type = Context->getObjCIdType();
3255 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3256 (void)convertBlockPointerToFunctionPointer(type);
3257 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3258 CastKind CK;
3259 if (SubExpr->getType()->isIntegralType(*Context) &&
3260 type->isBooleanType()) {
3261 CK = CK_IntegralToBoolean;
3262 } else if (type->isObjCObjectPointerType()) {
3263 if (SubExpr->getType()->isBlockPointerType()) {
3264 CK = CK_BlockPointerToObjCPointerCast;
3265 } else if (SubExpr->getType()->isPointerType()) {
3266 CK = CK_CPointerToObjCPointerCast;
3267 } else {
3268 CK = CK_BitCast;
3269 }
3270 } else {
3271 CK = CK_BitCast;
3272 }
3273
3274 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3275 }
3276 // Make id<P...> cast into an 'id' cast.
3277 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3278 if (CE->getType()->isObjCQualifiedIdType()) {
3279 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3280 userExpr = CE->getSubExpr();
3281 CastKind CK;
3282 if (userExpr->getType()->isIntegralType(*Context)) {
3283 CK = CK_IntegralToPointer;
3284 } else if (userExpr->getType()->isBlockPointerType()) {
3285 CK = CK_BlockPointerToObjCPointerCast;
3286 } else if (userExpr->getType()->isPointerType()) {
3287 CK = CK_CPointerToObjCPointerCast;
3288 } else {
3289 CK = CK_BitCast;
3290 }
3291 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3292 CK, userExpr);
3293 }
3294 }
3295 MsgExprs.push_back(userExpr);
3296 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3297 // out the argument in the original expression (since we aren't deleting
3298 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3299 //Exp->setArg(i, 0);
3300 }
3301 // Generate the funky cast.
3302 CastExpr *cast;
3303 SmallVector<QualType, 8> ArgTypes;
3304 QualType returnType;
3305
3306 // Push 'id' and 'SEL', the 2 implicit arguments.
3307 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3308 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3309 else
3310 ArgTypes.push_back(Context->getObjCIdType());
3311 ArgTypes.push_back(Context->getObjCSelType());
3312 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3313 // Push any user argument types.
3314 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3315 E = OMD->param_end(); PI != E; ++PI) {
3316 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3317 ? Context->getObjCIdType()
3318 : (*PI)->getType();
3319 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3320 (void)convertBlockPointerToFunctionPointer(t);
3321 ArgTypes.push_back(t);
3322 }
3323 returnType = Exp->getType();
3324 convertToUnqualifiedObjCType(returnType);
3325 (void)convertBlockPointerToFunctionPointer(returnType);
3326 } else {
3327 returnType = Context->getObjCIdType();
3328 }
3329 // Get the type, we will need to reference it in a couple spots.
3330 QualType msgSendType = MsgSendFlavor->getType();
3331
3332 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003333 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003334 VK_LValue, SourceLocation());
3335
3336 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3337 // If we don't do this cast, we get the following bizarre warning/note:
3338 // xx.m:13: warning: function called through a non-compatible type
3339 // xx.m:13: note: if this code is reached, the program will abort
3340 cast = NoTypeInfoCStyleCastExpr(Context,
3341 Context->getPointerType(Context->VoidTy),
3342 CK_BitCast, DRE);
3343
3344 // Now do the "normal" pointer to function cast.
3345 QualType castType =
3346 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3347 // If we don't have a method decl, force a variadic cast.
3348 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3349 castType = Context->getPointerType(castType);
3350 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3351 cast);
3352
3353 // Don't forget the parens to enforce the proper binding.
3354 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3355
3356 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3357 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3358 MsgExprs.size(),
3359 FT->getResultType(), VK_RValue,
3360 EndLoc);
3361 Stmt *ReplacingStmt = CE;
3362 if (MsgSendStretFlavor) {
3363 // We have the method which returns a struct/union. Must also generate
3364 // call to objc_msgSend_stret and hang both varieties on a conditional
3365 // expression which dictate which one to envoke depending on size of
3366 // method's return type.
3367
3368 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003369 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3370 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003371 VK_LValue, SourceLocation());
3372 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3373 cast = NoTypeInfoCStyleCastExpr(Context,
3374 Context->getPointerType(Context->VoidTy),
3375 CK_BitCast, STDRE);
3376 // Now do the "normal" pointer to function cast.
3377 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3378 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3379 castType = Context->getPointerType(castType);
3380 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3381 cast);
3382
3383 // Don't forget the parens to enforce the proper binding.
3384 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3385
3386 FT = msgSendType->getAs<FunctionType>();
3387 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3388 MsgExprs.size(),
3389 FT->getResultType(), VK_RValue,
3390 SourceLocation());
3391
3392 // Build sizeof(returnType)
3393 UnaryExprOrTypeTraitExpr *sizeofExpr =
3394 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3395 Context->getTrivialTypeSourceInfo(returnType),
3396 Context->getSizeType(), SourceLocation(),
3397 SourceLocation());
3398 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3399 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3400 // For X86 it is more complicated and some kind of target specific routine
3401 // is needed to decide what to do.
3402 unsigned IntSize =
3403 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3404 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3405 llvm::APInt(IntSize, 8),
3406 Context->IntTy,
3407 SourceLocation());
3408 BinaryOperator *lessThanExpr =
3409 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3410 VK_RValue, OK_Ordinary, SourceLocation());
3411 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3412 ConditionalOperator *CondExpr =
3413 new (Context) ConditionalOperator(lessThanExpr,
3414 SourceLocation(), CE,
3415 SourceLocation(), STCE,
3416 returnType, VK_RValue, OK_Ordinary);
3417 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3418 CondExpr);
3419 }
3420 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3421 return ReplacingStmt;
3422}
3423
3424Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3425 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3426 Exp->getLocEnd());
3427
3428 // Now do the actual rewrite.
3429 ReplaceStmt(Exp, ReplacingStmt);
3430
3431 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3432 return ReplacingStmt;
3433}
3434
3435// typedef struct objc_object Protocol;
3436QualType RewriteModernObjC::getProtocolType() {
3437 if (!ProtocolTypeDecl) {
3438 TypeSourceInfo *TInfo
3439 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3440 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3441 SourceLocation(), SourceLocation(),
3442 &Context->Idents.get("Protocol"),
3443 TInfo);
3444 }
3445 return Context->getTypeDeclType(ProtocolTypeDecl);
3446}
3447
3448/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3449/// a synthesized/forward data reference (to the protocol's metadata).
3450/// The forward references (and metadata) are generated in
3451/// RewriteModernObjC::HandleTranslationUnit().
3452Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003453 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3454 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003455 IdentifierInfo *ID = &Context->Idents.get(Name);
3456 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3457 SourceLocation(), ID, getProtocolType(), 0,
3458 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003459 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3460 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003461 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3462 Context->getPointerType(DRE->getType()),
3463 VK_RValue, OK_Ordinary, SourceLocation());
3464 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3465 CK_BitCast,
3466 DerefExpr);
3467 ReplaceStmt(Exp, castExpr);
3468 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3469 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3470 return castExpr;
3471
3472}
3473
3474bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3475 const char *endBuf) {
3476 while (startBuf < endBuf) {
3477 if (*startBuf == '#') {
3478 // Skip whitespace.
3479 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3480 ;
3481 if (!strncmp(startBuf, "if", strlen("if")) ||
3482 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3483 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3484 !strncmp(startBuf, "define", strlen("define")) ||
3485 !strncmp(startBuf, "undef", strlen("undef")) ||
3486 !strncmp(startBuf, "else", strlen("else")) ||
3487 !strncmp(startBuf, "elif", strlen("elif")) ||
3488 !strncmp(startBuf, "endif", strlen("endif")) ||
3489 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3490 !strncmp(startBuf, "include", strlen("include")) ||
3491 !strncmp(startBuf, "import", strlen("import")) ||
3492 !strncmp(startBuf, "include_next", strlen("include_next")))
3493 return true;
3494 }
3495 startBuf++;
3496 }
3497 return false;
3498}
3499
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003500/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003501/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003502bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3503 std::string &Result) {
3504 if (Type->isArrayType()) {
3505 QualType ElemTy = Context->getBaseElementType(Type);
3506 return RewriteObjCFieldDeclType(ElemTy, Result);
3507 }
3508 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003509 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3510 if (RD->isCompleteDefinition()) {
3511 if (RD->isStruct())
3512 Result += "\n\tstruct ";
3513 else if (RD->isUnion())
3514 Result += "\n\tunion ";
3515 else
3516 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003517
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003518 Result += RD->getName();
3519 if (TagsDefinedInIvarDecls.count(RD)) {
3520 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003521 Result += " ";
3522 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003523 }
3524 TagsDefinedInIvarDecls.insert(RD);
3525 Result += " {\n";
3526 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003527 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003528 FieldDecl *FD = *i;
3529 RewriteObjCFieldDecl(FD, Result);
3530 }
3531 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003532 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003533 }
3534 }
3535 else if (Type->isEnumeralType()) {
3536 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3537 if (ED->isCompleteDefinition()) {
3538 Result += "\n\tenum ";
3539 Result += ED->getName();
3540 if (TagsDefinedInIvarDecls.count(ED)) {
3541 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003542 Result += " ";
3543 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003544 }
3545 TagsDefinedInIvarDecls.insert(ED);
3546
3547 Result += " {\n";
3548 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3549 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3550 Result += "\t"; Result += EC->getName(); Result += " = ";
3551 llvm::APSInt Val = EC->getInitVal();
3552 Result += Val.toString(10);
3553 Result += ",\n";
3554 }
3555 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003556 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003557 }
3558 }
3559
3560 Result += "\t";
3561 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003562 return false;
3563}
3564
3565
3566/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3567/// It handles elaborated types, as well as enum types in the process.
3568void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3569 std::string &Result) {
3570 QualType Type = fieldDecl->getType();
3571 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003572
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003573 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3574 if (!EleboratedType)
3575 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003576 Result += Name;
3577 if (fieldDecl->isBitField()) {
3578 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3579 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003580 else if (EleboratedType && Type->isArrayType()) {
3581 CanQualType CType = Context->getCanonicalType(Type);
3582 while (isa<ArrayType>(CType)) {
3583 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3584 Result += "[";
3585 llvm::APInt Dim = CAT->getSize();
3586 Result += utostr(Dim.getZExtValue());
3587 Result += "]";
3588 }
3589 CType = CType->getAs<ArrayType>()->getElementType();
3590 }
3591 }
3592
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003593 Result += ";\n";
3594}
3595
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003596/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3597/// an objective-c class with ivars.
3598void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3599 std::string &Result) {
3600 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3601 assert(CDecl->getName() != "" &&
3602 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003603 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003604 SmallVector<ObjCIvarDecl *, 8> IVars;
3605 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003606 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003607 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003608
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003609 SourceLocation LocStart = CDecl->getLocStart();
3610 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003611
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003612 const char *startBuf = SM->getCharacterData(LocStart);
3613 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003614
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003615 // If no ivars and no root or if its root, directly or indirectly,
3616 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003617 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003618 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3619 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3620 ReplaceText(LocStart, endBuf-startBuf, Result);
3621 return;
3622 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003623
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003624 Result += "\nstruct ";
3625 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003626 Result += "_IMPL {\n";
3627
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003628 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003629 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3630 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3631 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003632 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003633 TagsDefinedInIvarDecls.clear();
3634 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3635 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003636
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003637 Result += "};\n";
3638 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3639 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003640 // Mark this struct as having been generated.
3641 if (!ObjCSynthesizedStructs.insert(CDecl))
3642 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003643}
3644
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003645static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3646 ObjCIvarDecl *IvarDecl, std::string &Result) {
3647 Result += "OBJC_IVAR_$_";
3648 Result += IDecl->getName();
3649 Result += "$";
3650 Result += IvarDecl->getName();
3651}
3652
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003653/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3654/// have been referenced in an ivar access expression.
3655void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3656 std::string &Result) {
3657 // write out ivar offset symbols which have been referenced in an ivar
3658 // access expression.
3659 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3660 if (Ivars.empty())
3661 return;
3662 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3663 e = Ivars.end(); i != e; i++) {
3664 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003665 Result += "\n";
3666 if (LangOpts.MicrosoftExt)
3667 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003668 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003669 if (LangOpts.MicrosoftExt &&
3670 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003671 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3672 Result += "__declspec(dllimport) ";
3673
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003674 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003675 WriteInternalIvarName(CDecl, IvarDecl, Result);
3676 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003677 }
3678}
3679
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003680//===----------------------------------------------------------------------===//
3681// Meta Data Emission
3682//===----------------------------------------------------------------------===//
3683
3684
3685/// RewriteImplementations - This routine rewrites all method implementations
3686/// and emits meta-data.
3687
3688void RewriteModernObjC::RewriteImplementations() {
3689 int ClsDefCount = ClassImplementation.size();
3690 int CatDefCount = CategoryImplementation.size();
3691
3692 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003693 for (int i = 0; i < ClsDefCount; i++) {
3694 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3695 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3696 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003697 assert(false &&
3698 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003699 RewriteImplementationDecl(OIMP);
3700 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003701
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003702 for (int i = 0; i < CatDefCount; i++) {
3703 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3704 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3705 if (CDecl->isImplicitInterfaceDecl())
3706 assert(false &&
3707 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003708 RewriteImplementationDecl(CIMP);
3709 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003710}
3711
3712void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3713 const std::string &Name,
3714 ValueDecl *VD, bool def) {
3715 assert(BlockByRefDeclNo.count(VD) &&
3716 "RewriteByRefString: ByRef decl missing");
3717 if (def)
3718 ResultStr += "struct ";
3719 ResultStr += "__Block_byref_" + Name +
3720 "_" + utostr(BlockByRefDeclNo[VD]) ;
3721}
3722
3723static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3724 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3725 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3726 return false;
3727}
3728
3729std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3730 StringRef funcName,
3731 std::string Tag) {
3732 const FunctionType *AFT = CE->getFunctionType();
3733 QualType RT = AFT->getResultType();
3734 std::string StructRef = "struct " + Tag;
3735 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003736 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003737
3738 BlockDecl *BD = CE->getBlockDecl();
3739
3740 if (isa<FunctionNoProtoType>(AFT)) {
3741 // No user-supplied arguments. Still need to pass in a pointer to the
3742 // block (to reference imported block decl refs).
3743 S += "(" + StructRef + " *__cself)";
3744 } else if (BD->param_empty()) {
3745 S += "(" + StructRef + " *__cself)";
3746 } else {
3747 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3748 assert(FT && "SynthesizeBlockFunc: No function proto");
3749 S += '(';
3750 // first add the implicit argument.
3751 S += StructRef + " *__cself, ";
3752 std::string ParamStr;
3753 for (BlockDecl::param_iterator AI = BD->param_begin(),
3754 E = BD->param_end(); AI != E; ++AI) {
3755 if (AI != BD->param_begin()) S += ", ";
3756 ParamStr = (*AI)->getNameAsString();
3757 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003758 (void)convertBlockPointerToFunctionPointer(QT);
3759 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003760 S += ParamStr;
3761 }
3762 if (FT->isVariadic()) {
3763 if (!BD->param_empty()) S += ", ";
3764 S += "...";
3765 }
3766 S += ')';
3767 }
3768 S += " {\n";
3769
3770 // Create local declarations to avoid rewriting all closure decl ref exprs.
3771 // First, emit a declaration for all "by ref" decls.
3772 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3773 E = BlockByRefDecls.end(); I != E; ++I) {
3774 S += " ";
3775 std::string Name = (*I)->getNameAsString();
3776 std::string TypeString;
3777 RewriteByRefString(TypeString, Name, (*I));
3778 TypeString += " *";
3779 Name = TypeString + Name;
3780 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3781 }
3782 // Next, emit a declaration for all "by copy" declarations.
3783 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3784 E = BlockByCopyDecls.end(); I != E; ++I) {
3785 S += " ";
3786 // Handle nested closure invocation. For example:
3787 //
3788 // void (^myImportedClosure)(void);
3789 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3790 //
3791 // void (^anotherClosure)(void);
3792 // anotherClosure = ^(void) {
3793 // myImportedClosure(); // import and invoke the closure
3794 // };
3795 //
3796 if (isTopLevelBlockPointerType((*I)->getType())) {
3797 RewriteBlockPointerTypeVariable(S, (*I));
3798 S += " = (";
3799 RewriteBlockPointerType(S, (*I)->getType());
3800 S += ")";
3801 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3802 }
3803 else {
3804 std::string Name = (*I)->getNameAsString();
3805 QualType QT = (*I)->getType();
3806 if (HasLocalVariableExternalStorage(*I))
3807 QT = Context->getPointerType(QT);
3808 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3809 S += Name + " = __cself->" +
3810 (*I)->getNameAsString() + "; // bound by copy\n";
3811 }
3812 }
3813 std::string RewrittenStr = RewrittenBlockExprs[CE];
3814 const char *cstr = RewrittenStr.c_str();
3815 while (*cstr++ != '{') ;
3816 S += cstr;
3817 S += "\n";
3818 return S;
3819}
3820
3821std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3822 StringRef funcName,
3823 std::string Tag) {
3824 std::string StructRef = "struct " + Tag;
3825 std::string S = "static void __";
3826
3827 S += funcName;
3828 S += "_block_copy_" + utostr(i);
3829 S += "(" + StructRef;
3830 S += "*dst, " + StructRef;
3831 S += "*src) {";
3832 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3833 E = ImportedBlockDecls.end(); I != E; ++I) {
3834 ValueDecl *VD = (*I);
3835 S += "_Block_object_assign((void*)&dst->";
3836 S += (*I)->getNameAsString();
3837 S += ", (void*)src->";
3838 S += (*I)->getNameAsString();
3839 if (BlockByRefDeclsPtrSet.count((*I)))
3840 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3841 else if (VD->getType()->isBlockPointerType())
3842 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3843 else
3844 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3845 }
3846 S += "}\n";
3847
3848 S += "\nstatic void __";
3849 S += funcName;
3850 S += "_block_dispose_" + utostr(i);
3851 S += "(" + StructRef;
3852 S += "*src) {";
3853 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3854 E = ImportedBlockDecls.end(); I != E; ++I) {
3855 ValueDecl *VD = (*I);
3856 S += "_Block_object_dispose((void*)src->";
3857 S += (*I)->getNameAsString();
3858 if (BlockByRefDeclsPtrSet.count((*I)))
3859 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3860 else if (VD->getType()->isBlockPointerType())
3861 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3862 else
3863 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3864 }
3865 S += "}\n";
3866 return S;
3867}
3868
3869std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3870 std::string Desc) {
3871 std::string S = "\nstruct " + Tag;
3872 std::string Constructor = " " + Tag;
3873
3874 S += " {\n struct __block_impl impl;\n";
3875 S += " struct " + Desc;
3876 S += "* Desc;\n";
3877
3878 Constructor += "(void *fp, "; // Invoke function pointer.
3879 Constructor += "struct " + Desc; // Descriptor pointer.
3880 Constructor += " *desc";
3881
3882 if (BlockDeclRefs.size()) {
3883 // Output all "by copy" declarations.
3884 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3885 E = BlockByCopyDecls.end(); I != E; ++I) {
3886 S += " ";
3887 std::string FieldName = (*I)->getNameAsString();
3888 std::string ArgName = "_" + FieldName;
3889 // Handle nested closure invocation. For example:
3890 //
3891 // void (^myImportedBlock)(void);
3892 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3893 //
3894 // void (^anotherBlock)(void);
3895 // anotherBlock = ^(void) {
3896 // myImportedBlock(); // import and invoke the closure
3897 // };
3898 //
3899 if (isTopLevelBlockPointerType((*I)->getType())) {
3900 S += "struct __block_impl *";
3901 Constructor += ", void *" + ArgName;
3902 } else {
3903 QualType QT = (*I)->getType();
3904 if (HasLocalVariableExternalStorage(*I))
3905 QT = Context->getPointerType(QT);
3906 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3907 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3908 Constructor += ", " + ArgName;
3909 }
3910 S += FieldName + ";\n";
3911 }
3912 // Output all "by ref" declarations.
3913 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3914 E = BlockByRefDecls.end(); I != E; ++I) {
3915 S += " ";
3916 std::string FieldName = (*I)->getNameAsString();
3917 std::string ArgName = "_" + FieldName;
3918 {
3919 std::string TypeString;
3920 RewriteByRefString(TypeString, FieldName, (*I));
3921 TypeString += " *";
3922 FieldName = TypeString + FieldName;
3923 ArgName = TypeString + ArgName;
3924 Constructor += ", " + ArgName;
3925 }
3926 S += FieldName + "; // by ref\n";
3927 }
3928 // Finish writing the constructor.
3929 Constructor += ", int flags=0)";
3930 // Initialize all "by copy" arguments.
3931 bool firsTime = true;
3932 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3933 E = BlockByCopyDecls.end(); I != E; ++I) {
3934 std::string Name = (*I)->getNameAsString();
3935 if (firsTime) {
3936 Constructor += " : ";
3937 firsTime = false;
3938 }
3939 else
3940 Constructor += ", ";
3941 if (isTopLevelBlockPointerType((*I)->getType()))
3942 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3943 else
3944 Constructor += Name + "(_" + Name + ")";
3945 }
3946 // Initialize all "by ref" arguments.
3947 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3948 E = BlockByRefDecls.end(); I != E; ++I) {
3949 std::string Name = (*I)->getNameAsString();
3950 if (firsTime) {
3951 Constructor += " : ";
3952 firsTime = false;
3953 }
3954 else
3955 Constructor += ", ";
3956 Constructor += Name + "(_" + Name + "->__forwarding)";
3957 }
3958
3959 Constructor += " {\n";
3960 if (GlobalVarDecl)
3961 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3962 else
3963 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3964 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3965
3966 Constructor += " Desc = desc;\n";
3967 } else {
3968 // Finish writing the constructor.
3969 Constructor += ", int flags=0) {\n";
3970 if (GlobalVarDecl)
3971 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3972 else
3973 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3974 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3975 Constructor += " Desc = desc;\n";
3976 }
3977 Constructor += " ";
3978 Constructor += "}\n";
3979 S += Constructor;
3980 S += "};\n";
3981 return S;
3982}
3983
3984std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3985 std::string ImplTag, int i,
3986 StringRef FunName,
3987 unsigned hasCopy) {
3988 std::string S = "\nstatic struct " + DescTag;
3989
3990 S += " {\n unsigned long reserved;\n";
3991 S += " unsigned long Block_size;\n";
3992 if (hasCopy) {
3993 S += " void (*copy)(struct ";
3994 S += ImplTag; S += "*, struct ";
3995 S += ImplTag; S += "*);\n";
3996
3997 S += " void (*dispose)(struct ";
3998 S += ImplTag; S += "*);\n";
3999 }
4000 S += "} ";
4001
4002 S += DescTag + "_DATA = { 0, sizeof(struct ";
4003 S += ImplTag + ")";
4004 if (hasCopy) {
4005 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4006 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4007 }
4008 S += "};\n";
4009 return S;
4010}
4011
4012void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4013 StringRef FunName) {
4014 // Insert declaration for the function in which block literal is used.
4015 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4016 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4017 bool RewriteSC = (GlobalVarDecl &&
4018 !Blocks.empty() &&
4019 GlobalVarDecl->getStorageClass() == SC_Static &&
4020 GlobalVarDecl->getType().getCVRQualifiers());
4021 if (RewriteSC) {
4022 std::string SC(" void __");
4023 SC += GlobalVarDecl->getNameAsString();
4024 SC += "() {}";
4025 InsertText(FunLocStart, SC);
4026 }
4027
4028 // Insert closures that were part of the function.
4029 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4030 CollectBlockDeclRefInfo(Blocks[i]);
4031 // Need to copy-in the inner copied-in variables not actually used in this
4032 // block.
4033 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004034 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004035 ValueDecl *VD = Exp->getDecl();
4036 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004037 if (!VD->hasAttr<BlocksAttr>()) {
4038 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4039 BlockByCopyDeclsPtrSet.insert(VD);
4040 BlockByCopyDecls.push_back(VD);
4041 }
4042 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004043 }
John McCallf4b88a42012-03-10 09:33:50 +00004044
4045 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004046 BlockByRefDeclsPtrSet.insert(VD);
4047 BlockByRefDecls.push_back(VD);
4048 }
John McCallf4b88a42012-03-10 09:33:50 +00004049
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004050 // imported objects in the inner blocks not used in the outer
4051 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004052 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004053 VD->getType()->isBlockPointerType())
4054 ImportedBlockDecls.insert(VD);
4055 }
4056
4057 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4058 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4059
4060 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4061
4062 InsertText(FunLocStart, CI);
4063
4064 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4065
4066 InsertText(FunLocStart, CF);
4067
4068 if (ImportedBlockDecls.size()) {
4069 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4070 InsertText(FunLocStart, HF);
4071 }
4072 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4073 ImportedBlockDecls.size() > 0);
4074 InsertText(FunLocStart, BD);
4075
4076 BlockDeclRefs.clear();
4077 BlockByRefDecls.clear();
4078 BlockByRefDeclsPtrSet.clear();
4079 BlockByCopyDecls.clear();
4080 BlockByCopyDeclsPtrSet.clear();
4081 ImportedBlockDecls.clear();
4082 }
4083 if (RewriteSC) {
4084 // Must insert any 'const/volatile/static here. Since it has been
4085 // removed as result of rewriting of block literals.
4086 std::string SC;
4087 if (GlobalVarDecl->getStorageClass() == SC_Static)
4088 SC = "static ";
4089 if (GlobalVarDecl->getType().isConstQualified())
4090 SC += "const ";
4091 if (GlobalVarDecl->getType().isVolatileQualified())
4092 SC += "volatile ";
4093 if (GlobalVarDecl->getType().isRestrictQualified())
4094 SC += "restrict ";
4095 InsertText(FunLocStart, SC);
4096 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004097 if (GlobalConstructionExp) {
4098 // extra fancy dance for global literal expression.
4099
4100 // Always the latest block expression on the block stack.
4101 std::string Tag = "__";
4102 Tag += FunName;
4103 Tag += "_block_impl_";
4104 Tag += utostr(Blocks.size()-1);
4105 std::string globalBuf = "static ";
4106 globalBuf += Tag; globalBuf += " ";
4107 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004108
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004109 llvm::raw_string_ostream constructorExprBuf(SStr);
4110 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4111 PrintingPolicy(LangOpts));
4112 globalBuf += constructorExprBuf.str();
4113 globalBuf += ";\n";
4114 InsertText(FunLocStart, globalBuf);
4115 GlobalConstructionExp = 0;
4116 }
4117
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004118 Blocks.clear();
4119 InnerDeclRefsCount.clear();
4120 InnerDeclRefs.clear();
4121 RewrittenBlockExprs.clear();
4122}
4123
4124void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4125 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
4126 StringRef FuncName = FD->getName();
4127
4128 SynthesizeBlockLiterals(FunLocStart, FuncName);
4129}
4130
4131static void BuildUniqueMethodName(std::string &Name,
4132 ObjCMethodDecl *MD) {
4133 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4134 Name = IFace->getName();
4135 Name += "__" + MD->getSelector().getAsString();
4136 // Convert colons to underscores.
4137 std::string::size_type loc = 0;
4138 while ((loc = Name.find(":", loc)) != std::string::npos)
4139 Name.replace(loc, 1, "_");
4140}
4141
4142void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4143 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4144 //SourceLocation FunLocStart = MD->getLocStart();
4145 SourceLocation FunLocStart = MD->getLocStart();
4146 std::string FuncName;
4147 BuildUniqueMethodName(FuncName, MD);
4148 SynthesizeBlockLiterals(FunLocStart, FuncName);
4149}
4150
4151void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4152 for (Stmt::child_range CI = S->children(); CI; ++CI)
4153 if (*CI) {
4154 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4155 GetBlockDeclRefExprs(CBE->getBody());
4156 else
4157 GetBlockDeclRefExprs(*CI);
4158 }
4159 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004160 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4161 if (DRE->refersToEnclosingLocal() &&
4162 HasLocalVariableExternalStorage(DRE->getDecl())) {
4163 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004164 }
4165
4166 return;
4167}
4168
4169void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004170 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004171 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4172 for (Stmt::child_range CI = S->children(); CI; ++CI)
4173 if (*CI) {
4174 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4175 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4176 GetInnerBlockDeclRefExprs(CBE->getBody(),
4177 InnerBlockDeclRefs,
4178 InnerContexts);
4179 }
4180 else
4181 GetInnerBlockDeclRefExprs(*CI,
4182 InnerBlockDeclRefs,
4183 InnerContexts);
4184
4185 }
4186 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004187 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4188 if (DRE->refersToEnclosingLocal()) {
4189 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4190 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4191 InnerBlockDeclRefs.push_back(DRE);
4192 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4193 if (Var->isFunctionOrMethodVarDecl())
4194 ImportedLocalExternalDecls.insert(Var);
4195 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004196 }
4197
4198 return;
4199}
4200
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004201/// convertObjCTypeToCStyleType - This routine converts such objc types
4202/// as qualified objects, and blocks to their closest c/c++ types that
4203/// it can. It returns true if input type was modified.
4204bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4205 QualType oldT = T;
4206 convertBlockPointerToFunctionPointer(T);
4207 if (T->isFunctionPointerType()) {
4208 QualType PointeeTy;
4209 if (const PointerType* PT = T->getAs<PointerType>()) {
4210 PointeeTy = PT->getPointeeType();
4211 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4212 T = convertFunctionTypeOfBlocks(FT);
4213 T = Context->getPointerType(T);
4214 }
4215 }
4216 }
4217
4218 convertToUnqualifiedObjCType(T);
4219 return T != oldT;
4220}
4221
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004222/// convertFunctionTypeOfBlocks - This routine converts a function type
4223/// whose result type may be a block pointer or whose argument type(s)
4224/// might be block pointers to an equivalent function type replacing
4225/// all block pointers to function pointers.
4226QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4227 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4228 // FTP will be null for closures that don't take arguments.
4229 // Generate a funky cast.
4230 SmallVector<QualType, 8> ArgTypes;
4231 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004232 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004233
4234 if (FTP) {
4235 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4236 E = FTP->arg_type_end(); I && (I != E); ++I) {
4237 QualType t = *I;
4238 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004239 if (convertObjCTypeToCStyleType(t))
4240 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004241 ArgTypes.push_back(t);
4242 }
4243 }
4244 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004245 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004246 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4247 else FuncType = QualType(FT, 0);
4248 return FuncType;
4249}
4250
4251Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4252 // Navigate to relevant type information.
4253 const BlockPointerType *CPT = 0;
4254
4255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4256 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004257 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4258 CPT = MExpr->getType()->getAs<BlockPointerType>();
4259 }
4260 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4261 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4262 }
4263 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4264 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4265 else if (const ConditionalOperator *CEXPR =
4266 dyn_cast<ConditionalOperator>(BlockExp)) {
4267 Expr *LHSExp = CEXPR->getLHS();
4268 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4269 Expr *RHSExp = CEXPR->getRHS();
4270 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4271 Expr *CONDExp = CEXPR->getCond();
4272 ConditionalOperator *CondExpr =
4273 new (Context) ConditionalOperator(CONDExp,
4274 SourceLocation(), cast<Expr>(LHSStmt),
4275 SourceLocation(), cast<Expr>(RHSStmt),
4276 Exp->getType(), VK_RValue, OK_Ordinary);
4277 return CondExpr;
4278 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4279 CPT = IRE->getType()->getAs<BlockPointerType>();
4280 } else if (const PseudoObjectExpr *POE
4281 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4282 CPT = POE->getType()->castAs<BlockPointerType>();
4283 } else {
4284 assert(1 && "RewriteBlockClass: Bad type");
4285 }
4286 assert(CPT && "RewriteBlockClass: Bad type");
4287 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4288 assert(FT && "RewriteBlockClass: Bad type");
4289 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4290 // FTP will be null for closures that don't take arguments.
4291
4292 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4293 SourceLocation(), SourceLocation(),
4294 &Context->Idents.get("__block_impl"));
4295 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4296
4297 // Generate a funky cast.
4298 SmallVector<QualType, 8> ArgTypes;
4299
4300 // Push the block argument type.
4301 ArgTypes.push_back(PtrBlock);
4302 if (FTP) {
4303 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4304 E = FTP->arg_type_end(); I && (I != E); ++I) {
4305 QualType t = *I;
4306 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4307 if (!convertBlockPointerToFunctionPointer(t))
4308 convertToUnqualifiedObjCType(t);
4309 ArgTypes.push_back(t);
4310 }
4311 }
4312 // Now do the pointer to function cast.
4313 QualType PtrToFuncCastType
4314 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4315
4316 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4317
4318 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4319 CK_BitCast,
4320 const_cast<Expr*>(BlockExp));
4321 // Don't forget the parens to enforce the proper binding.
4322 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4323 BlkCast);
4324 //PE->dump();
4325
4326 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4327 SourceLocation(),
4328 &Context->Idents.get("FuncPtr"),
4329 Context->VoidPtrTy, 0,
4330 /*BitWidth=*/0, /*Mutable=*/true,
4331 /*HasInit=*/false);
4332 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4333 FD->getType(), VK_LValue,
4334 OK_Ordinary);
4335
4336
4337 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4338 CK_BitCast, ME);
4339 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4340
4341 SmallVector<Expr*, 8> BlkExprs;
4342 // Add the implicit argument.
4343 BlkExprs.push_back(BlkCast);
4344 // Add the user arguments.
4345 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4346 E = Exp->arg_end(); I != E; ++I) {
4347 BlkExprs.push_back(*I);
4348 }
4349 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4350 BlkExprs.size(),
4351 Exp->getType(), VK_RValue,
4352 SourceLocation());
4353 return CE;
4354}
4355
4356// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004357// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004358// For example:
4359//
4360// int main() {
4361// __block Foo *f;
4362// __block int i;
4363//
4364// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004365// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004366// i = 77;
4367// };
4368//}
John McCallf4b88a42012-03-10 09:33:50 +00004369Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004370 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4371 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004372 ValueDecl *VD = DeclRefExp->getDecl();
4373 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004374
4375 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4376 SourceLocation(),
4377 &Context->Idents.get("__forwarding"),
4378 Context->VoidPtrTy, 0,
4379 /*BitWidth=*/0, /*Mutable=*/true,
4380 /*HasInit=*/false);
4381 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4382 FD, SourceLocation(),
4383 FD->getType(), VK_LValue,
4384 OK_Ordinary);
4385
4386 StringRef Name = VD->getName();
4387 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4388 &Context->Idents.get(Name),
4389 Context->VoidPtrTy, 0,
4390 /*BitWidth=*/0, /*Mutable=*/true,
4391 /*HasInit=*/false);
4392 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4393 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4394
4395
4396
4397 // Need parens to enforce precedence.
4398 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4399 DeclRefExp->getExprLoc(),
4400 ME);
4401 ReplaceStmt(DeclRefExp, PE);
4402 return PE;
4403}
4404
4405// Rewrites the imported local variable V with external storage
4406// (static, extern, etc.) as *V
4407//
4408Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4409 ValueDecl *VD = DRE->getDecl();
4410 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4411 if (!ImportedLocalExternalDecls.count(Var))
4412 return DRE;
4413 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4414 VK_LValue, OK_Ordinary,
4415 DRE->getLocation());
4416 // Need parens to enforce precedence.
4417 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4418 Exp);
4419 ReplaceStmt(DRE, PE);
4420 return PE;
4421}
4422
4423void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4424 SourceLocation LocStart = CE->getLParenLoc();
4425 SourceLocation LocEnd = CE->getRParenLoc();
4426
4427 // Need to avoid trying to rewrite synthesized casts.
4428 if (LocStart.isInvalid())
4429 return;
4430 // Need to avoid trying to rewrite casts contained in macros.
4431 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4432 return;
4433
4434 const char *startBuf = SM->getCharacterData(LocStart);
4435 const char *endBuf = SM->getCharacterData(LocEnd);
4436 QualType QT = CE->getType();
4437 const Type* TypePtr = QT->getAs<Type>();
4438 if (isa<TypeOfExprType>(TypePtr)) {
4439 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4440 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4441 std::string TypeAsString = "(";
4442 RewriteBlockPointerType(TypeAsString, QT);
4443 TypeAsString += ")";
4444 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4445 return;
4446 }
4447 // advance the location to startArgList.
4448 const char *argPtr = startBuf;
4449
4450 while (*argPtr++ && (argPtr < endBuf)) {
4451 switch (*argPtr) {
4452 case '^':
4453 // Replace the '^' with '*'.
4454 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4455 ReplaceText(LocStart, 1, "*");
4456 break;
4457 }
4458 }
4459 return;
4460}
4461
4462void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4463 SourceLocation DeclLoc = FD->getLocation();
4464 unsigned parenCount = 0;
4465
4466 // We have 1 or more arguments that have closure pointers.
4467 const char *startBuf = SM->getCharacterData(DeclLoc);
4468 const char *startArgList = strchr(startBuf, '(');
4469
4470 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4471
4472 parenCount++;
4473 // advance the location to startArgList.
4474 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4475 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4476
4477 const char *argPtr = startArgList;
4478
4479 while (*argPtr++ && parenCount) {
4480 switch (*argPtr) {
4481 case '^':
4482 // Replace the '^' with '*'.
4483 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4484 ReplaceText(DeclLoc, 1, "*");
4485 break;
4486 case '(':
4487 parenCount++;
4488 break;
4489 case ')':
4490 parenCount--;
4491 break;
4492 }
4493 }
4494 return;
4495}
4496
4497bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4498 const FunctionProtoType *FTP;
4499 const PointerType *PT = QT->getAs<PointerType>();
4500 if (PT) {
4501 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4502 } else {
4503 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4504 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4505 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4506 }
4507 if (FTP) {
4508 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4509 E = FTP->arg_type_end(); I != E; ++I)
4510 if (isTopLevelBlockPointerType(*I))
4511 return true;
4512 }
4513 return false;
4514}
4515
4516bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4517 const FunctionProtoType *FTP;
4518 const PointerType *PT = QT->getAs<PointerType>();
4519 if (PT) {
4520 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4521 } else {
4522 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4523 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4524 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4525 }
4526 if (FTP) {
4527 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4528 E = FTP->arg_type_end(); I != E; ++I) {
4529 if ((*I)->isObjCQualifiedIdType())
4530 return true;
4531 if ((*I)->isObjCObjectPointerType() &&
4532 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4533 return true;
4534 }
4535
4536 }
4537 return false;
4538}
4539
4540void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4541 const char *&RParen) {
4542 const char *argPtr = strchr(Name, '(');
4543 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4544
4545 LParen = argPtr; // output the start.
4546 argPtr++; // skip past the left paren.
4547 unsigned parenCount = 1;
4548
4549 while (*argPtr && parenCount) {
4550 switch (*argPtr) {
4551 case '(': parenCount++; break;
4552 case ')': parenCount--; break;
4553 default: break;
4554 }
4555 if (parenCount) argPtr++;
4556 }
4557 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4558 RParen = argPtr; // output the end
4559}
4560
4561void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4562 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4563 RewriteBlockPointerFunctionArgs(FD);
4564 return;
4565 }
4566 // Handle Variables and Typedefs.
4567 SourceLocation DeclLoc = ND->getLocation();
4568 QualType DeclT;
4569 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4570 DeclT = VD->getType();
4571 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4572 DeclT = TDD->getUnderlyingType();
4573 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4574 DeclT = FD->getType();
4575 else
4576 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4577
4578 const char *startBuf = SM->getCharacterData(DeclLoc);
4579 const char *endBuf = startBuf;
4580 // scan backward (from the decl location) for the end of the previous decl.
4581 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4582 startBuf--;
4583 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4584 std::string buf;
4585 unsigned OrigLength=0;
4586 // *startBuf != '^' if we are dealing with a pointer to function that
4587 // may take block argument types (which will be handled below).
4588 if (*startBuf == '^') {
4589 // Replace the '^' with '*', computing a negative offset.
4590 buf = '*';
4591 startBuf++;
4592 OrigLength++;
4593 }
4594 while (*startBuf != ')') {
4595 buf += *startBuf;
4596 startBuf++;
4597 OrigLength++;
4598 }
4599 buf += ')';
4600 OrigLength++;
4601
4602 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4603 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4604 // Replace the '^' with '*' for arguments.
4605 // Replace id<P> with id/*<>*/
4606 DeclLoc = ND->getLocation();
4607 startBuf = SM->getCharacterData(DeclLoc);
4608 const char *argListBegin, *argListEnd;
4609 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4610 while (argListBegin < argListEnd) {
4611 if (*argListBegin == '^')
4612 buf += '*';
4613 else if (*argListBegin == '<') {
4614 buf += "/*";
4615 buf += *argListBegin++;
4616 OrigLength++;;
4617 while (*argListBegin != '>') {
4618 buf += *argListBegin++;
4619 OrigLength++;
4620 }
4621 buf += *argListBegin;
4622 buf += "*/";
4623 }
4624 else
4625 buf += *argListBegin;
4626 argListBegin++;
4627 OrigLength++;
4628 }
4629 buf += ')';
4630 OrigLength++;
4631 }
4632 ReplaceText(Start, OrigLength, buf);
4633
4634 return;
4635}
4636
4637
4638/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4639/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4640/// struct Block_byref_id_object *src) {
4641/// _Block_object_assign (&_dest->object, _src->object,
4642/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4643/// [|BLOCK_FIELD_IS_WEAK]) // object
4644/// _Block_object_assign(&_dest->object, _src->object,
4645/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4646/// [|BLOCK_FIELD_IS_WEAK]) // block
4647/// }
4648/// And:
4649/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4650/// _Block_object_dispose(_src->object,
4651/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4652/// [|BLOCK_FIELD_IS_WEAK]) // object
4653/// _Block_object_dispose(_src->object,
4654/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4655/// [|BLOCK_FIELD_IS_WEAK]) // block
4656/// }
4657
4658std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4659 int flag) {
4660 std::string S;
4661 if (CopyDestroyCache.count(flag))
4662 return S;
4663 CopyDestroyCache.insert(flag);
4664 S = "static void __Block_byref_id_object_copy_";
4665 S += utostr(flag);
4666 S += "(void *dst, void *src) {\n";
4667
4668 // offset into the object pointer is computed as:
4669 // void * + void* + int + int + void* + void *
4670 unsigned IntSize =
4671 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4672 unsigned VoidPtrSize =
4673 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4674
4675 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4676 S += " _Block_object_assign((char*)dst + ";
4677 S += utostr(offset);
4678 S += ", *(void * *) ((char*)src + ";
4679 S += utostr(offset);
4680 S += "), ";
4681 S += utostr(flag);
4682 S += ");\n}\n";
4683
4684 S += "static void __Block_byref_id_object_dispose_";
4685 S += utostr(flag);
4686 S += "(void *src) {\n";
4687 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4688 S += utostr(offset);
4689 S += "), ";
4690 S += utostr(flag);
4691 S += ");\n}\n";
4692 return S;
4693}
4694
4695/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4696/// the declaration into:
4697/// struct __Block_byref_ND {
4698/// void *__isa; // NULL for everything except __weak pointers
4699/// struct __Block_byref_ND *__forwarding;
4700/// int32_t __flags;
4701/// int32_t __size;
4702/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4703/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4704/// typex ND;
4705/// };
4706///
4707/// It then replaces declaration of ND variable with:
4708/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4709/// __size=sizeof(struct __Block_byref_ND),
4710/// ND=initializer-if-any};
4711///
4712///
4713void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4714 // Insert declaration for the function in which block literal is
4715 // used.
4716 if (CurFunctionDeclToDeclareForBlock)
4717 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4718 int flag = 0;
4719 int isa = 0;
4720 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4721 if (DeclLoc.isInvalid())
4722 // If type location is missing, it is because of missing type (a warning).
4723 // Use variable's location which is good for this case.
4724 DeclLoc = ND->getLocation();
4725 const char *startBuf = SM->getCharacterData(DeclLoc);
4726 SourceLocation X = ND->getLocEnd();
4727 X = SM->getExpansionLoc(X);
4728 const char *endBuf = SM->getCharacterData(X);
4729 std::string Name(ND->getNameAsString());
4730 std::string ByrefType;
4731 RewriteByRefString(ByrefType, Name, ND, true);
4732 ByrefType += " {\n";
4733 ByrefType += " void *__isa;\n";
4734 RewriteByRefString(ByrefType, Name, ND);
4735 ByrefType += " *__forwarding;\n";
4736 ByrefType += " int __flags;\n";
4737 ByrefType += " int __size;\n";
4738 // Add void *__Block_byref_id_object_copy;
4739 // void *__Block_byref_id_object_dispose; if needed.
4740 QualType Ty = ND->getType();
4741 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4742 if (HasCopyAndDispose) {
4743 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4744 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4745 }
4746
4747 QualType T = Ty;
4748 (void)convertBlockPointerToFunctionPointer(T);
4749 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4750
4751 ByrefType += " " + Name + ";\n";
4752 ByrefType += "};\n";
4753 // Insert this type in global scope. It is needed by helper function.
4754 SourceLocation FunLocStart;
4755 if (CurFunctionDef)
4756 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4757 else {
4758 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4759 FunLocStart = CurMethodDef->getLocStart();
4760 }
4761 InsertText(FunLocStart, ByrefType);
4762 if (Ty.isObjCGCWeak()) {
4763 flag |= BLOCK_FIELD_IS_WEAK;
4764 isa = 1;
4765 }
4766
4767 if (HasCopyAndDispose) {
4768 flag = BLOCK_BYREF_CALLER;
4769 QualType Ty = ND->getType();
4770 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4771 if (Ty->isBlockPointerType())
4772 flag |= BLOCK_FIELD_IS_BLOCK;
4773 else
4774 flag |= BLOCK_FIELD_IS_OBJECT;
4775 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4776 if (!HF.empty())
4777 InsertText(FunLocStart, HF);
4778 }
4779
4780 // struct __Block_byref_ND ND =
4781 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4782 // initializer-if-any};
4783 bool hasInit = (ND->getInit() != 0);
4784 unsigned flags = 0;
4785 if (HasCopyAndDispose)
4786 flags |= BLOCK_HAS_COPY_DISPOSE;
4787 Name = ND->getNameAsString();
4788 ByrefType.clear();
4789 RewriteByRefString(ByrefType, Name, ND);
4790 std::string ForwardingCastType("(");
4791 ForwardingCastType += ByrefType + " *)";
4792 if (!hasInit) {
4793 ByrefType += " " + Name + " = {(void*)";
4794 ByrefType += utostr(isa);
4795 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4796 ByrefType += utostr(flags);
4797 ByrefType += ", ";
4798 ByrefType += "sizeof(";
4799 RewriteByRefString(ByrefType, Name, ND);
4800 ByrefType += ")";
4801 if (HasCopyAndDispose) {
4802 ByrefType += ", __Block_byref_id_object_copy_";
4803 ByrefType += utostr(flag);
4804 ByrefType += ", __Block_byref_id_object_dispose_";
4805 ByrefType += utostr(flag);
4806 }
4807 ByrefType += "};\n";
4808 unsigned nameSize = Name.size();
4809 // for block or function pointer declaration. Name is aleady
4810 // part of the declaration.
4811 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4812 nameSize = 1;
4813 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4814 }
4815 else {
4816 SourceLocation startLoc;
4817 Expr *E = ND->getInit();
4818 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4819 startLoc = ECE->getLParenLoc();
4820 else
4821 startLoc = E->getLocStart();
4822 startLoc = SM->getExpansionLoc(startLoc);
4823 endBuf = SM->getCharacterData(startLoc);
4824 ByrefType += " " + Name;
4825 ByrefType += " = {(void*)";
4826 ByrefType += utostr(isa);
4827 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4828 ByrefType += utostr(flags);
4829 ByrefType += ", ";
4830 ByrefType += "sizeof(";
4831 RewriteByRefString(ByrefType, Name, ND);
4832 ByrefType += "), ";
4833 if (HasCopyAndDispose) {
4834 ByrefType += "__Block_byref_id_object_copy_";
4835 ByrefType += utostr(flag);
4836 ByrefType += ", __Block_byref_id_object_dispose_";
4837 ByrefType += utostr(flag);
4838 ByrefType += ", ";
4839 }
4840 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4841
4842 // Complete the newly synthesized compound expression by inserting a right
4843 // curly brace before the end of the declaration.
4844 // FIXME: This approach avoids rewriting the initializer expression. It
4845 // also assumes there is only one declarator. For example, the following
4846 // isn't currently supported by this routine (in general):
4847 //
4848 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4849 //
4850 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4851 const char *semiBuf = strchr(startInitializerBuf, ';');
4852 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4853 SourceLocation semiLoc =
4854 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4855
4856 InsertText(semiLoc, "}");
4857 }
4858 return;
4859}
4860
4861void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4862 // Add initializers for any closure decl refs.
4863 GetBlockDeclRefExprs(Exp->getBody());
4864 if (BlockDeclRefs.size()) {
4865 // Unique all "by copy" declarations.
4866 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004867 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004868 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4869 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4870 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4871 }
4872 }
4873 // Unique all "by ref" declarations.
4874 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004875 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004876 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4877 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4878 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4879 }
4880 }
4881 // Find any imported blocks...they will need special attention.
4882 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004883 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004884 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4885 BlockDeclRefs[i]->getType()->isBlockPointerType())
4886 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4887 }
4888}
4889
4890FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4891 IdentifierInfo *ID = &Context->Idents.get(name);
4892 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4893 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4894 SourceLocation(), ID, FType, 0, SC_Extern,
4895 SC_None, false, false);
4896}
4897
4898Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004899 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004901 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004902
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004903 Blocks.push_back(Exp);
4904
4905 CollectBlockDeclRefInfo(Exp);
4906
4907 // Add inner imported variables now used in current block.
4908 int countOfInnerDecls = 0;
4909 if (!InnerBlockDeclRefs.empty()) {
4910 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004911 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004912 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004913 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004914 // We need to save the copied-in variables in nested
4915 // blocks because it is needed at the end for some of the API generations.
4916 // See SynthesizeBlockLiterals routine.
4917 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4918 BlockDeclRefs.push_back(Exp);
4919 BlockByCopyDeclsPtrSet.insert(VD);
4920 BlockByCopyDecls.push_back(VD);
4921 }
John McCallf4b88a42012-03-10 09:33:50 +00004922 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004923 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4924 BlockDeclRefs.push_back(Exp);
4925 BlockByRefDeclsPtrSet.insert(VD);
4926 BlockByRefDecls.push_back(VD);
4927 }
4928 }
4929 // Find any imported blocks...they will need special attention.
4930 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004931 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004932 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4933 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4934 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4935 }
4936 InnerDeclRefsCount.push_back(countOfInnerDecls);
4937
4938 std::string FuncName;
4939
4940 if (CurFunctionDef)
4941 FuncName = CurFunctionDef->getNameAsString();
4942 else if (CurMethodDef)
4943 BuildUniqueMethodName(FuncName, CurMethodDef);
4944 else if (GlobalVarDecl)
4945 FuncName = std::string(GlobalVarDecl->getNameAsString());
4946
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004947 bool GlobalBlockExpr =
4948 block->getDeclContext()->getRedeclContext()->isFileContext();
4949
4950 if (GlobalBlockExpr && !GlobalVarDecl) {
4951 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4952 GlobalBlockExpr = false;
4953 }
4954
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004955 std::string BlockNumber = utostr(Blocks.size()-1);
4956
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004957 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4958
4959 // Get a pointer to the function type so we can cast appropriately.
4960 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4961 QualType FType = Context->getPointerType(BFT);
4962
4963 FunctionDecl *FD;
4964 Expr *NewRep;
4965
4966 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004967 std::string Tag;
4968
4969 if (GlobalBlockExpr)
4970 Tag = "__global_";
4971 else
4972 Tag = "__";
4973 Tag += FuncName + "_block_impl_" + BlockNumber;
4974
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004975 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004976 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004977 SourceLocation());
4978
4979 SmallVector<Expr*, 4> InitExprs;
4980
4981 // Initialize the block function.
4982 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004983 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4984 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004985 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4986 CK_BitCast, Arg);
4987 InitExprs.push_back(castExpr);
4988
4989 // Initialize the block descriptor.
4990 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4991
4992 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4993 SourceLocation(), SourceLocation(),
4994 &Context->Idents.get(DescData.c_str()),
4995 Context->VoidPtrTy, 0,
4996 SC_Static, SC_None);
4997 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004998 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004999 Context->VoidPtrTy,
5000 VK_LValue,
5001 SourceLocation()),
5002 UO_AddrOf,
5003 Context->getPointerType(Context->VoidPtrTy),
5004 VK_RValue, OK_Ordinary,
5005 SourceLocation());
5006 InitExprs.push_back(DescRefExpr);
5007
5008 // Add initializers for any closure decl refs.
5009 if (BlockDeclRefs.size()) {
5010 Expr *Exp;
5011 // Output all "by copy" declarations.
5012 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5013 E = BlockByCopyDecls.end(); I != E; ++I) {
5014 if (isObjCType((*I)->getType())) {
5015 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5016 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005017 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5018 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005019 if (HasLocalVariableExternalStorage(*I)) {
5020 QualType QT = (*I)->getType();
5021 QT = Context->getPointerType(QT);
5022 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5023 OK_Ordinary, SourceLocation());
5024 }
5025 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5026 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005027 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5028 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005029 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5030 CK_BitCast, Arg);
5031 } else {
5032 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005033 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5034 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005035 if (HasLocalVariableExternalStorage(*I)) {
5036 QualType QT = (*I)->getType();
5037 QT = Context->getPointerType(QT);
5038 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5039 OK_Ordinary, SourceLocation());
5040 }
5041
5042 }
5043 InitExprs.push_back(Exp);
5044 }
5045 // Output all "by ref" declarations.
5046 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5047 E = BlockByRefDecls.end(); I != E; ++I) {
5048 ValueDecl *ND = (*I);
5049 std::string Name(ND->getNameAsString());
5050 std::string RecName;
5051 RewriteByRefString(RecName, Name, ND, true);
5052 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5053 + sizeof("struct"));
5054 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5055 SourceLocation(), SourceLocation(),
5056 II);
5057 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5058 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5059
5060 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005061 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005062 SourceLocation());
5063 bool isNestedCapturedVar = false;
5064 if (block)
5065 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5066 ce = block->capture_end(); ci != ce; ++ci) {
5067 const VarDecl *variable = ci->getVariable();
5068 if (variable == ND && ci->isNested()) {
5069 assert (ci->isByRef() &&
5070 "SynthBlockInitExpr - captured block variable is not byref");
5071 isNestedCapturedVar = true;
5072 break;
5073 }
5074 }
5075 // captured nested byref variable has its address passed. Do not take
5076 // its address again.
5077 if (!isNestedCapturedVar)
5078 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5079 Context->getPointerType(Exp->getType()),
5080 VK_RValue, OK_Ordinary, SourceLocation());
5081 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5082 InitExprs.push_back(Exp);
5083 }
5084 }
5085 if (ImportedBlockDecls.size()) {
5086 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5087 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5088 unsigned IntSize =
5089 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5090 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5091 Context->IntTy, SourceLocation());
5092 InitExprs.push_back(FlagExp);
5093 }
5094 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5095 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005096
5097 if (GlobalBlockExpr) {
5098 assert (GlobalConstructionExp == 0 &&
5099 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5100 GlobalConstructionExp = NewRep;
5101 NewRep = DRE;
5102 }
5103
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005104 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5105 Context->getPointerType(NewRep->getType()),
5106 VK_RValue, OK_Ordinary, SourceLocation());
5107 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5108 NewRep);
5109 BlockDeclRefs.clear();
5110 BlockByRefDecls.clear();
5111 BlockByRefDeclsPtrSet.clear();
5112 BlockByCopyDecls.clear();
5113 BlockByCopyDeclsPtrSet.clear();
5114 ImportedBlockDecls.clear();
5115 return NewRep;
5116}
5117
5118bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5119 if (const ObjCForCollectionStmt * CS =
5120 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5121 return CS->getElement() == DS;
5122 return false;
5123}
5124
5125//===----------------------------------------------------------------------===//
5126// Function Body / Expression rewriting
5127//===----------------------------------------------------------------------===//
5128
5129Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5130 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5131 isa<DoStmt>(S) || isa<ForStmt>(S))
5132 Stmts.push_back(S);
5133 else if (isa<ObjCForCollectionStmt>(S)) {
5134 Stmts.push_back(S);
5135 ObjCBcLabelNo.push_back(++BcLabelCount);
5136 }
5137
5138 // Pseudo-object operations and ivar references need special
5139 // treatment because we're going to recursively rewrite them.
5140 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5141 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5142 return RewritePropertyOrImplicitSetter(PseudoOp);
5143 } else {
5144 return RewritePropertyOrImplicitGetter(PseudoOp);
5145 }
5146 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5147 return RewriteObjCIvarRefExpr(IvarRefExpr);
5148 }
5149
5150 SourceRange OrigStmtRange = S->getSourceRange();
5151
5152 // Perform a bottom up rewrite of all children.
5153 for (Stmt::child_range CI = S->children(); CI; ++CI)
5154 if (*CI) {
5155 Stmt *childStmt = (*CI);
5156 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5157 if (newStmt) {
5158 *CI = newStmt;
5159 }
5160 }
5161
5162 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005163 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005164 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5165 InnerContexts.insert(BE->getBlockDecl());
5166 ImportedLocalExternalDecls.clear();
5167 GetInnerBlockDeclRefExprs(BE->getBody(),
5168 InnerBlockDeclRefs, InnerContexts);
5169 // Rewrite the block body in place.
5170 Stmt *SaveCurrentBody = CurrentBody;
5171 CurrentBody = BE->getBody();
5172 PropParentMap = 0;
5173 // block literal on rhs of a property-dot-sytax assignment
5174 // must be replaced by its synthesize ast so getRewrittenText
5175 // works as expected. In this case, what actually ends up on RHS
5176 // is the blockTranscribed which is the helper function for the
5177 // block literal; as in: self.c = ^() {[ace ARR];};
5178 bool saveDisableReplaceStmt = DisableReplaceStmt;
5179 DisableReplaceStmt = false;
5180 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5181 DisableReplaceStmt = saveDisableReplaceStmt;
5182 CurrentBody = SaveCurrentBody;
5183 PropParentMap = 0;
5184 ImportedLocalExternalDecls.clear();
5185 // Now we snarf the rewritten text and stash it away for later use.
5186 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5187 RewrittenBlockExprs[BE] = Str;
5188
5189 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5190
5191 //blockTranscribed->dump();
5192 ReplaceStmt(S, blockTranscribed);
5193 return blockTranscribed;
5194 }
5195 // Handle specific things.
5196 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5197 return RewriteAtEncode(AtEncode);
5198
5199 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5200 return RewriteAtSelector(AtSelector);
5201
5202 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5203 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005204
5205 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5206 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005207
5208 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
5209 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005210
5211 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5212 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005213
5214 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5215 dyn_cast<ObjCDictionaryLiteral>(S))
5216 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005217
5218 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5219#if 0
5220 // Before we rewrite it, put the original message expression in a comment.
5221 SourceLocation startLoc = MessExpr->getLocStart();
5222 SourceLocation endLoc = MessExpr->getLocEnd();
5223
5224 const char *startBuf = SM->getCharacterData(startLoc);
5225 const char *endBuf = SM->getCharacterData(endLoc);
5226
5227 std::string messString;
5228 messString += "// ";
5229 messString.append(startBuf, endBuf-startBuf+1);
5230 messString += "\n";
5231
5232 // FIXME: Missing definition of
5233 // InsertText(clang::SourceLocation, char const*, unsigned int).
5234 // InsertText(startLoc, messString.c_str(), messString.size());
5235 // Tried this, but it didn't work either...
5236 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5237#endif
5238 return RewriteMessageExpr(MessExpr);
5239 }
5240
5241 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5242 return RewriteObjCTryStmt(StmtTry);
5243
5244 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5245 return RewriteObjCSynchronizedStmt(StmtTry);
5246
5247 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5248 return RewriteObjCThrowStmt(StmtThrow);
5249
5250 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5251 return RewriteObjCProtocolExpr(ProtocolExp);
5252
5253 if (ObjCForCollectionStmt *StmtForCollection =
5254 dyn_cast<ObjCForCollectionStmt>(S))
5255 return RewriteObjCForCollectionStmt(StmtForCollection,
5256 OrigStmtRange.getEnd());
5257 if (BreakStmt *StmtBreakStmt =
5258 dyn_cast<BreakStmt>(S))
5259 return RewriteBreakStmt(StmtBreakStmt);
5260 if (ContinueStmt *StmtContinueStmt =
5261 dyn_cast<ContinueStmt>(S))
5262 return RewriteContinueStmt(StmtContinueStmt);
5263
5264 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5265 // and cast exprs.
5266 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5267 // FIXME: What we're doing here is modifying the type-specifier that
5268 // precedes the first Decl. In the future the DeclGroup should have
5269 // a separate type-specifier that we can rewrite.
5270 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5271 // the context of an ObjCForCollectionStmt. For example:
5272 // NSArray *someArray;
5273 // for (id <FooProtocol> index in someArray) ;
5274 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5275 // and it depends on the original text locations/positions.
5276 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5277 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5278
5279 // Blocks rewrite rules.
5280 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5281 DI != DE; ++DI) {
5282 Decl *SD = *DI;
5283 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5284 if (isTopLevelBlockPointerType(ND->getType()))
5285 RewriteBlockPointerDecl(ND);
5286 else if (ND->getType()->isFunctionPointerType())
5287 CheckFunctionPointerDecl(ND->getType(), ND);
5288 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5289 if (VD->hasAttr<BlocksAttr>()) {
5290 static unsigned uniqueByrefDeclCount = 0;
5291 assert(!BlockByRefDeclNo.count(ND) &&
5292 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5293 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5294 RewriteByRefVar(VD);
5295 }
5296 else
5297 RewriteTypeOfDecl(VD);
5298 }
5299 }
5300 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5301 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5302 RewriteBlockPointerDecl(TD);
5303 else if (TD->getUnderlyingType()->isFunctionPointerType())
5304 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5305 }
5306 }
5307 }
5308
5309 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5310 RewriteObjCQualifiedInterfaceTypes(CE);
5311
5312 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5313 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5314 assert(!Stmts.empty() && "Statement stack is empty");
5315 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5316 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5317 && "Statement stack mismatch");
5318 Stmts.pop_back();
5319 }
5320 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5322 ValueDecl *VD = DRE->getDecl();
5323 if (VD->hasAttr<BlocksAttr>())
5324 return RewriteBlockDeclRefExpr(DRE);
5325 if (HasLocalVariableExternalStorage(VD))
5326 return RewriteLocalVariableExternalStorage(DRE);
5327 }
5328
5329 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5330 if (CE->getCallee()->getType()->isBlockPointerType()) {
5331 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5332 ReplaceStmt(S, BlockCall);
5333 return BlockCall;
5334 }
5335 }
5336 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5337 RewriteCastExpr(CE);
5338 }
5339#if 0
5340 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5341 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5342 ICE->getSubExpr(),
5343 SourceLocation());
5344 // Get the new text.
5345 std::string SStr;
5346 llvm::raw_string_ostream Buf(SStr);
5347 Replacement->printPretty(Buf, *Context);
5348 const std::string &Str = Buf.str();
5349
5350 printf("CAST = %s\n", &Str[0]);
5351 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5352 delete S;
5353 return Replacement;
5354 }
5355#endif
5356 // Return this stmt unmodified.
5357 return S;
5358}
5359
5360void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5361 for (RecordDecl::field_iterator i = RD->field_begin(),
5362 e = RD->field_end(); i != e; ++i) {
5363 FieldDecl *FD = *i;
5364 if (isTopLevelBlockPointerType(FD->getType()))
5365 RewriteBlockPointerDecl(FD);
5366 if (FD->getType()->isObjCQualifiedIdType() ||
5367 FD->getType()->isObjCQualifiedInterfaceType())
5368 RewriteObjCQualifiedInterfaceTypes(FD);
5369 }
5370}
5371
5372/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5373/// main file of the input.
5374void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5375 switch (D->getKind()) {
5376 case Decl::Function: {
5377 FunctionDecl *FD = cast<FunctionDecl>(D);
5378 if (FD->isOverloadedOperator())
5379 return;
5380
5381 // Since function prototypes don't have ParmDecl's, we check the function
5382 // prototype. This enables us to rewrite function declarations and
5383 // definitions using the same code.
5384 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5385
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005386 if (!FD->isThisDeclarationADefinition())
5387 break;
5388
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005389 // FIXME: If this should support Obj-C++, support CXXTryStmt
5390 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5391 CurFunctionDef = FD;
5392 CurFunctionDeclToDeclareForBlock = FD;
5393 CurrentBody = Body;
5394 Body =
5395 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5396 FD->setBody(Body);
5397 CurrentBody = 0;
5398 if (PropParentMap) {
5399 delete PropParentMap;
5400 PropParentMap = 0;
5401 }
5402 // This synthesizes and inserts the block "impl" struct, invoke function,
5403 // and any copy/dispose helper functions.
5404 InsertBlockLiteralsWithinFunction(FD);
5405 CurFunctionDef = 0;
5406 CurFunctionDeclToDeclareForBlock = 0;
5407 }
5408 break;
5409 }
5410 case Decl::ObjCMethod: {
5411 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5412 if (CompoundStmt *Body = MD->getCompoundBody()) {
5413 CurMethodDef = MD;
5414 CurrentBody = Body;
5415 Body =
5416 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5417 MD->setBody(Body);
5418 CurrentBody = 0;
5419 if (PropParentMap) {
5420 delete PropParentMap;
5421 PropParentMap = 0;
5422 }
5423 InsertBlockLiteralsWithinMethod(MD);
5424 CurMethodDef = 0;
5425 }
5426 break;
5427 }
5428 case Decl::ObjCImplementation: {
5429 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5430 ClassImplementation.push_back(CI);
5431 break;
5432 }
5433 case Decl::ObjCCategoryImpl: {
5434 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5435 CategoryImplementation.push_back(CI);
5436 break;
5437 }
5438 case Decl::Var: {
5439 VarDecl *VD = cast<VarDecl>(D);
5440 RewriteObjCQualifiedInterfaceTypes(VD);
5441 if (isTopLevelBlockPointerType(VD->getType()))
5442 RewriteBlockPointerDecl(VD);
5443 else if (VD->getType()->isFunctionPointerType()) {
5444 CheckFunctionPointerDecl(VD->getType(), VD);
5445 if (VD->getInit()) {
5446 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5447 RewriteCastExpr(CE);
5448 }
5449 }
5450 } else if (VD->getType()->isRecordType()) {
5451 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5452 if (RD->isCompleteDefinition())
5453 RewriteRecordBody(RD);
5454 }
5455 if (VD->getInit()) {
5456 GlobalVarDecl = VD;
5457 CurrentBody = VD->getInit();
5458 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5459 CurrentBody = 0;
5460 if (PropParentMap) {
5461 delete PropParentMap;
5462 PropParentMap = 0;
5463 }
5464 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5465 GlobalVarDecl = 0;
5466
5467 // This is needed for blocks.
5468 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5469 RewriteCastExpr(CE);
5470 }
5471 }
5472 break;
5473 }
5474 case Decl::TypeAlias:
5475 case Decl::Typedef: {
5476 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5477 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5478 RewriteBlockPointerDecl(TD);
5479 else if (TD->getUnderlyingType()->isFunctionPointerType())
5480 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5481 }
5482 break;
5483 }
5484 case Decl::CXXRecord:
5485 case Decl::Record: {
5486 RecordDecl *RD = cast<RecordDecl>(D);
5487 if (RD->isCompleteDefinition())
5488 RewriteRecordBody(RD);
5489 break;
5490 }
5491 default:
5492 break;
5493 }
5494 // Nothing yet.
5495}
5496
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005497/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5498/// protocol reference symbols in the for of:
5499/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5500static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5501 ObjCProtocolDecl *PDecl,
5502 std::string &Result) {
5503 // Also output .objc_protorefs$B section and its meta-data.
5504 if (Context->getLangOpts().MicrosoftExt)
5505 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5506 Result += "struct _protocol_t *";
5507 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5508 Result += PDecl->getNameAsString();
5509 Result += " = &";
5510 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5511 Result += ";\n";
5512}
5513
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005514void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5515 if (Diags.hasErrorOccurred())
5516 return;
5517
5518 RewriteInclude();
5519
5520 // Here's a great place to add any extra declarations that may be needed.
5521 // Write out meta data for each @protocol(<expr>).
5522 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005523 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005524 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005525 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5526 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005527
5528 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005529 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5530 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5531 // Write struct declaration for the class matching its ivar declarations.
5532 // Note that for modern abi, this is postponed until the end of TU
5533 // because class extensions and the implementation might declare their own
5534 // private ivars.
5535 RewriteInterfaceDecl(CDecl);
5536 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005537
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005538 if (ClassImplementation.size() || CategoryImplementation.size())
5539 RewriteImplementations();
5540
5541 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5542 // we are done.
5543 if (const RewriteBuffer *RewriteBuf =
5544 Rewrite.getRewriteBufferFor(MainFileID)) {
5545 //printf("Changed:\n");
5546 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5547 } else {
5548 llvm::errs() << "No changes\n";
5549 }
5550
5551 if (ClassImplementation.size() || CategoryImplementation.size() ||
5552 ProtocolExprDecls.size()) {
5553 // Rewrite Objective-c meta data*
5554 std::string ResultStr;
5555 RewriteMetaDataIntoBuffer(ResultStr);
5556 // Emit metadata.
5557 *OutFile << ResultStr;
5558 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005559 // Emit ImageInfo;
5560 {
5561 std::string ResultStr;
5562 WriteImageInfo(ResultStr);
5563 *OutFile << ResultStr;
5564 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005565 OutFile->flush();
5566}
5567
5568void RewriteModernObjC::Initialize(ASTContext &context) {
5569 InitializeCommon(context);
5570
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005571 Preamble += "#ifndef __OBJC2__\n";
5572 Preamble += "#define __OBJC2__\n";
5573 Preamble += "#endif\n";
5574
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005575 // declaring objc_selector outside the parameter list removes a silly
5576 // scope related warning...
5577 if (IsHeader)
5578 Preamble = "#pragma once\n";
5579 Preamble += "struct objc_selector; struct objc_class;\n";
5580 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5581 Preamble += "struct objc_object *superClass; ";
5582 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005583 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005584 // These are currently generated.
5585 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005586 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005587 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5588 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005589 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5590 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005591 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005592 // These are generated but not necessary for functionality.
5593 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5594 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005595 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5596 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005597 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005598
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005599 // These need be generated for performance. Currently they are not,
5600 // using API calls instead.
5601 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5602 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5603 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5604
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005605 // Add a constructor for creating temporary objects.
5606 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5607 ": ";
5608 Preamble += "object(o), superClass(s) {} ";
5609 }
5610 Preamble += "};\n";
5611 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5612 Preamble += "typedef struct objc_object Protocol;\n";
5613 Preamble += "#define _REWRITER_typedef_Protocol\n";
5614 Preamble += "#endif\n";
5615 if (LangOpts.MicrosoftExt) {
5616 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5617 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005618 }
5619 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005620 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005621
5622 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5623 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5624 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5625 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5626 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5627
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005628 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5629 Preamble += "(const char *);\n";
5630 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5631 Preamble += "(struct objc_class *);\n";
5632 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5633 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005634 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005635 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005636 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5637 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005638 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5639 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5640 Preamble += "struct __objcFastEnumerationState {\n\t";
5641 Preamble += "unsigned long state;\n\t";
5642 Preamble += "void **itemsPtr;\n\t";
5643 Preamble += "unsigned long *mutationsPtr;\n\t";
5644 Preamble += "unsigned long extra[5];\n};\n";
5645 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5646 Preamble += "#define __FASTENUMERATIONSTATE\n";
5647 Preamble += "#endif\n";
5648 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5649 Preamble += "struct __NSConstantStringImpl {\n";
5650 Preamble += " int *isa;\n";
5651 Preamble += " int flags;\n";
5652 Preamble += " char *str;\n";
5653 Preamble += " long length;\n";
5654 Preamble += "};\n";
5655 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5656 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5657 Preamble += "#else\n";
5658 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5659 Preamble += "#endif\n";
5660 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5661 Preamble += "#endif\n";
5662 // Blocks preamble.
5663 Preamble += "#ifndef BLOCK_IMPL\n";
5664 Preamble += "#define BLOCK_IMPL\n";
5665 Preamble += "struct __block_impl {\n";
5666 Preamble += " void *isa;\n";
5667 Preamble += " int Flags;\n";
5668 Preamble += " int Reserved;\n";
5669 Preamble += " void *FuncPtr;\n";
5670 Preamble += "};\n";
5671 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5672 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5673 Preamble += "extern \"C\" __declspec(dllexport) "
5674 "void _Block_object_assign(void *, const void *, const int);\n";
5675 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5676 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5677 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5678 Preamble += "#else\n";
5679 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5680 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5681 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5682 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5683 Preamble += "#endif\n";
5684 Preamble += "#endif\n";
5685 if (LangOpts.MicrosoftExt) {
5686 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5687 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5688 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5689 Preamble += "#define __attribute__(X)\n";
5690 Preamble += "#endif\n";
5691 Preamble += "#define __weak\n";
5692 }
5693 else {
5694 Preamble += "#define __block\n";
5695 Preamble += "#define __weak\n";
5696 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005697
5698 // Declarations required for modern objective-c array and dictionary literals.
5699 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005700 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005701 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005702 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005703 Preamble += "\tva_list marker;\n";
5704 Preamble += "\tva_start(marker, count);\n";
5705 Preamble += "\tarr = new void *[count];\n";
5706 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5707 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5708 Preamble += "\tva_end( marker );\n";
5709 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005710 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005711 Preamble += "\tdelete[] arr;\n";
5712 Preamble += " }\n";
5713 Preamble += "};\n";
5714
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005715 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5716 // as this avoids warning in any 64bit/32bit compilation model.
5717 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5718}
5719
5720/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5721/// ivar offset.
5722void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5723 std::string &Result) {
5724 if (ivar->isBitField()) {
5725 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5726 // place all bitfields at offset 0.
5727 Result += "0";
5728 } else {
5729 Result += "__OFFSETOFIVAR__(struct ";
5730 Result += ivar->getContainingInterface()->getNameAsString();
5731 if (LangOpts.MicrosoftExt)
5732 Result += "_IMPL";
5733 Result += ", ";
5734 Result += ivar->getNameAsString();
5735 Result += ")";
5736 }
5737}
5738
5739/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5740/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005741/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005742/// char *attributes;
5743/// }
5744
5745/// struct _prop_list_t {
5746/// uint32_t entsize; // sizeof(struct _prop_t)
5747/// uint32_t count_of_properties;
5748/// struct _prop_t prop_list[count_of_properties];
5749/// }
5750
5751/// struct _protocol_t;
5752
5753/// struct _protocol_list_t {
5754/// long protocol_count; // Note, this is 32/64 bit
5755/// struct _protocol_t * protocol_list[protocol_count];
5756/// }
5757
5758/// struct _objc_method {
5759/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005760/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005761/// char *_imp;
5762/// }
5763
5764/// struct _method_list_t {
5765/// uint32_t entsize; // sizeof(struct _objc_method)
5766/// uint32_t method_count;
5767/// struct _objc_method method_list[method_count];
5768/// }
5769
5770/// struct _protocol_t {
5771/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005772/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005773/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005774/// const struct method_list_t *instance_methods;
5775/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005776/// const struct method_list_t *optionalInstanceMethods;
5777/// const struct method_list_t *optionalClassMethods;
5778/// const struct _prop_list_t * properties;
5779/// const uint32_t size; // sizeof(struct _protocol_t)
5780/// const uint32_t flags; // = 0
5781/// const char ** extendedMethodTypes;
5782/// }
5783
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005784/// struct _ivar_t {
5785/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005786/// const char *name;
5787/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005788/// uint32_t alignment;
5789/// uint32_t size;
5790/// }
5791
5792/// struct _ivar_list_t {
5793/// uint32 entsize; // sizeof(struct _ivar_t)
5794/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005795/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005796/// }
5797
5798/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005799/// uint32_t flags;
5800/// uint32_t instanceStart;
5801/// uint32_t instanceSize;
5802/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005803/// const uint8_t *ivarLayout;
5804/// const char *name;
5805/// const struct _method_list_t *baseMethods;
5806/// const struct _protocol_list_t *baseProtocols;
5807/// const struct _ivar_list_t *ivars;
5808/// const uint8_t *weakIvarLayout;
5809/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005810/// }
5811
5812/// struct _class_t {
5813/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005814/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005815/// void *cache;
5816/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005817/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005818/// }
5819
5820/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005821/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005822/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005823/// const struct _method_list_t *instance_methods;
5824/// const struct _method_list_t *class_methods;
5825/// const struct _protocol_list_t *protocols;
5826/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005827/// }
5828
5829/// MessageRefTy - LLVM for:
5830/// struct _message_ref_t {
5831/// IMP messenger;
5832/// SEL name;
5833/// };
5834
5835/// SuperMessageRefTy - LLVM for:
5836/// struct _super_message_ref_t {
5837/// SUPER_IMP messenger;
5838/// SEL name;
5839/// };
5840
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005841static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005842 static bool meta_data_declared = false;
5843 if (meta_data_declared)
5844 return;
5845
5846 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005847 Result += "\tconst char *name;\n";
5848 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005849 Result += "};\n";
5850
5851 Result += "\nstruct _protocol_t;\n";
5852
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005853 Result += "\nstruct _objc_method {\n";
5854 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005855 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005856 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005857 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005858
5859 Result += "\nstruct _protocol_t {\n";
5860 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005861 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005862 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005863 Result += "\tconst struct method_list_t *instance_methods;\n";
5864 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005865 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5866 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5867 Result += "\tconst struct _prop_list_t * properties;\n";
5868 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5869 Result += "\tconst unsigned int flags; // = 0\n";
5870 Result += "\tconst char ** extendedMethodTypes;\n";
5871 Result += "};\n";
5872
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005873 Result += "\nstruct _ivar_t {\n";
5874 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005875 Result += "\tconst char *name;\n";
5876 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005877 Result += "\tunsigned int alignment;\n";
5878 Result += "\tunsigned int size;\n";
5879 Result += "};\n";
5880
5881 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005882 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005883 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005884 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005885 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5886 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005887 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005888 Result += "\tconst unsigned char *ivarLayout;\n";
5889 Result += "\tconst char *name;\n";
5890 Result += "\tconst struct _method_list_t *baseMethods;\n";
5891 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5892 Result += "\tconst struct _ivar_list_t *ivars;\n";
5893 Result += "\tconst unsigned char *weakIvarLayout;\n";
5894 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005895 Result += "};\n";
5896
5897 Result += "\nstruct _class_t {\n";
5898 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005899 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005900 Result += "\tvoid *cache;\n";
5901 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005902 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005903 Result += "};\n";
5904
5905 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005906 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005907 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005908 Result += "\tconst struct _method_list_t *instance_methods;\n";
5909 Result += "\tconst struct _method_list_t *class_methods;\n";
5910 Result += "\tconst struct _protocol_list_t *protocols;\n";
5911 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005912 Result += "};\n";
5913
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005914 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005915 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005916 meta_data_declared = true;
5917}
5918
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005919static void Write_protocol_list_t_TypeDecl(std::string &Result,
5920 long super_protocol_count) {
5921 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5922 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5923 Result += "\tstruct _protocol_t *super_protocols[";
5924 Result += utostr(super_protocol_count); Result += "];\n";
5925 Result += "}";
5926}
5927
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005928static void Write_method_list_t_TypeDecl(std::string &Result,
5929 unsigned int method_count) {
5930 Result += "struct /*_method_list_t*/"; Result += " {\n";
5931 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5932 Result += "\tunsigned int method_count;\n";
5933 Result += "\tstruct _objc_method method_list[";
5934 Result += utostr(method_count); Result += "];\n";
5935 Result += "}";
5936}
5937
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005938static void Write__prop_list_t_TypeDecl(std::string &Result,
5939 unsigned int property_count) {
5940 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5941 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5942 Result += "\tunsigned int count_of_properties;\n";
5943 Result += "\tstruct _prop_t prop_list[";
5944 Result += utostr(property_count); Result += "];\n";
5945 Result += "}";
5946}
5947
Fariborz Jahanianae932952012-02-10 20:47:10 +00005948static void Write__ivar_list_t_TypeDecl(std::string &Result,
5949 unsigned int ivar_count) {
5950 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5951 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5952 Result += "\tunsigned int count;\n";
5953 Result += "\tstruct _ivar_t ivar_list[";
5954 Result += utostr(ivar_count); Result += "];\n";
5955 Result += "}";
5956}
5957
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005958static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5959 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5960 StringRef VarName,
5961 StringRef ProtocolName) {
5962 if (SuperProtocols.size() > 0) {
5963 Result += "\nstatic ";
5964 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5965 Result += " "; Result += VarName;
5966 Result += ProtocolName;
5967 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5968 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5969 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5970 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5971 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5972 Result += SuperPD->getNameAsString();
5973 if (i == e-1)
5974 Result += "\n};\n";
5975 else
5976 Result += ",\n";
5977 }
5978 }
5979}
5980
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005981static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5982 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005983 ArrayRef<ObjCMethodDecl *> Methods,
5984 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005985 StringRef TopLevelDeclName,
5986 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005987 if (Methods.size() > 0) {
5988 Result += "\nstatic ";
5989 Write_method_list_t_TypeDecl(Result, Methods.size());
5990 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005991 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005992 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5993 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5994 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5995 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5996 ObjCMethodDecl *MD = Methods[i];
5997 if (i == 0)
5998 Result += "\t{{(struct objc_selector *)\"";
5999 else
6000 Result += "\t{(struct objc_selector *)\"";
6001 Result += (MD)->getSelector().getAsString(); Result += "\"";
6002 Result += ", ";
6003 std::string MethodTypeString;
6004 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6005 Result += "\""; Result += MethodTypeString; Result += "\"";
6006 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006007 if (!MethodImpl)
6008 Result += "0";
6009 else {
6010 Result += "(void *)";
6011 Result += RewriteObj.MethodInternalNames[MD];
6012 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006013 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006014 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006015 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006016 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006017 }
6018 Result += "};\n";
6019 }
6020}
6021
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006022static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006023 ASTContext *Context, std::string &Result,
6024 ArrayRef<ObjCPropertyDecl *> Properties,
6025 const Decl *Container,
6026 StringRef VarName,
6027 StringRef ProtocolName) {
6028 if (Properties.size() > 0) {
6029 Result += "\nstatic ";
6030 Write__prop_list_t_TypeDecl(Result, Properties.size());
6031 Result += " "; Result += VarName;
6032 Result += ProtocolName;
6033 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6034 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6035 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6036 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6037 ObjCPropertyDecl *PropDecl = Properties[i];
6038 if (i == 0)
6039 Result += "\t{{\"";
6040 else
6041 Result += "\t{\"";
6042 Result += PropDecl->getName(); Result += "\",";
6043 std::string PropertyTypeString, QuotePropertyTypeString;
6044 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6045 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6046 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6047 if (i == e-1)
6048 Result += "}}\n";
6049 else
6050 Result += "},\n";
6051 }
6052 Result += "};\n";
6053 }
6054}
6055
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006056// Metadata flags
6057enum MetaDataDlags {
6058 CLS = 0x0,
6059 CLS_META = 0x1,
6060 CLS_ROOT = 0x2,
6061 OBJC2_CLS_HIDDEN = 0x10,
6062 CLS_EXCEPTION = 0x20,
6063
6064 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6065 CLS_HAS_IVAR_RELEASER = 0x40,
6066 /// class was compiled with -fobjc-arr
6067 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6068};
6069
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006070static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6071 unsigned int flags,
6072 const std::string &InstanceStart,
6073 const std::string &InstanceSize,
6074 ArrayRef<ObjCMethodDecl *>baseMethods,
6075 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6076 ArrayRef<ObjCIvarDecl *>ivars,
6077 ArrayRef<ObjCPropertyDecl *>Properties,
6078 StringRef VarName,
6079 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006080 Result += "\nstatic struct _class_ro_t ";
6081 Result += VarName; Result += ClassName;
6082 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6083 Result += "\t";
6084 Result += llvm::utostr(flags); Result += ", ";
6085 Result += InstanceStart; Result += ", ";
6086 Result += InstanceSize; Result += ", \n";
6087 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006088 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6089 if (Triple.getArch() == llvm::Triple::x86_64)
6090 // uint32_t const reserved; // only when building for 64bit targets
6091 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006092 // const uint8_t * const ivarLayout;
6093 Result += "0, \n\t";
6094 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006095 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006096 if (baseMethods.size() > 0) {
6097 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006098 if (metaclass)
6099 Result += "_OBJC_$_CLASS_METHODS_";
6100 else
6101 Result += "_OBJC_$_INSTANCE_METHODS_";
6102 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006103 Result += ",\n\t";
6104 }
6105 else
6106 Result += "0, \n\t";
6107
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006108 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006109 Result += "(const struct _objc_protocol_list *)&";
6110 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6111 Result += ",\n\t";
6112 }
6113 else
6114 Result += "0, \n\t";
6115
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006116 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006117 Result += "(const struct _ivar_list_t *)&";
6118 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6119 Result += ",\n\t";
6120 }
6121 else
6122 Result += "0, \n\t";
6123
6124 // weakIvarLayout
6125 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006126 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006127 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006128 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006129 Result += ",\n";
6130 }
6131 else
6132 Result += "0, \n";
6133
6134 Result += "};\n";
6135}
6136
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006137static void Write_class_t(ASTContext *Context, std::string &Result,
6138 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006139 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6140 bool rootClass = (!CDecl->getSuperClass());
6141 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006142
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006143 if (!rootClass) {
6144 // Find the Root class
6145 RootClass = CDecl->getSuperClass();
6146 while (RootClass->getSuperClass()) {
6147 RootClass = RootClass->getSuperClass();
6148 }
6149 }
6150
6151 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006152 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006153 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006154 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006155 if (CDecl->getImplementation())
6156 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006157 else
6158 Result += "__declspec(dllimport) ";
6159
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006160 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006161 Result += CDecl->getNameAsString();
6162 Result += ";\n";
6163 }
6164 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006165 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006166 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006167 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006168 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006169 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006170 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006171 else
6172 Result += "__declspec(dllimport) ";
6173
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006174 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006175 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006176 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006177 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006178
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006179 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006180 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006181 if (RootClass->getImplementation())
6182 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006183 else
6184 Result += "__declspec(dllimport) ";
6185
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006186 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006187 Result += VarName;
6188 Result += RootClass->getNameAsString();
6189 Result += ";\n";
6190 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006191 }
6192
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006193 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6194 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006195 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6196 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006197 if (metaclass) {
6198 if (!rootClass) {
6199 Result += "0, // &"; Result += VarName;
6200 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006201 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006202 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006203 Result += CDecl->getSuperClass()->getNameAsString();
6204 Result += ",\n\t";
6205 }
6206 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006207 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006208 Result += CDecl->getNameAsString();
6209 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006210 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006211 Result += ",\n\t";
6212 }
6213 }
6214 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006215 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006216 Result += CDecl->getNameAsString();
6217 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006218 if (!rootClass) {
6219 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006220 Result += CDecl->getSuperClass()->getNameAsString();
6221 Result += ",\n\t";
6222 }
6223 else
6224 Result += "0,\n\t";
6225 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006226 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6227 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6228 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006229 Result += "&_OBJC_METACLASS_RO_$_";
6230 else
6231 Result += "&_OBJC_CLASS_RO_$_";
6232 Result += CDecl->getNameAsString();
6233 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006234
6235 // Add static function to initialize some of the meta-data fields.
6236 // avoid doing it twice.
6237 if (metaclass)
6238 return;
6239
6240 const ObjCInterfaceDecl *SuperClass =
6241 rootClass ? CDecl : CDecl->getSuperClass();
6242
6243 Result += "static void OBJC_CLASS_SETUP_$_";
6244 Result += CDecl->getNameAsString();
6245 Result += "(void ) {\n";
6246 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6247 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006248 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006249
6250 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006251 Result += ".superclass = ";
6252 if (rootClass)
6253 Result += "&OBJC_CLASS_$_";
6254 else
6255 Result += "&OBJC_METACLASS_$_";
6256
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006257 Result += SuperClass->getNameAsString(); Result += ";\n";
6258
6259 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6260 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6261
6262 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6263 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6264 Result += CDecl->getNameAsString(); Result += ";\n";
6265
6266 if (!rootClass) {
6267 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6268 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6269 Result += SuperClass->getNameAsString(); Result += ";\n";
6270 }
6271
6272 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6273 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6274 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006275}
6276
Fariborz Jahanian61186122012-02-17 18:40:41 +00006277static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6278 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006279 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006280 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006281 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6282 ArrayRef<ObjCMethodDecl *> ClassMethods,
6283 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6284 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006285 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006286 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006287 // must declare an extern class object in case this class is not implemented
6288 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006289 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006290 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006291 if (ClassDecl->getImplementation())
6292 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006293 else
6294 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006295
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006296 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006297 Result += "OBJC_CLASS_$_"; Result += ClassName;
6298 Result += ";\n";
6299
Fariborz Jahanian61186122012-02-17 18:40:41 +00006300 Result += "\nstatic struct _category_t ";
6301 Result += "_OBJC_$_CATEGORY_";
6302 Result += ClassName; Result += "_$_"; Result += CatName;
6303 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6304 Result += "{\n";
6305 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006306 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006307 Result += ",\n";
6308 if (InstanceMethods.size() > 0) {
6309 Result += "\t(const struct _method_list_t *)&";
6310 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6311 Result += ClassName; Result += "_$_"; Result += CatName;
6312 Result += ",\n";
6313 }
6314 else
6315 Result += "\t0,\n";
6316
6317 if (ClassMethods.size() > 0) {
6318 Result += "\t(const struct _method_list_t *)&";
6319 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6320 Result += ClassName; Result += "_$_"; Result += CatName;
6321 Result += ",\n";
6322 }
6323 else
6324 Result += "\t0,\n";
6325
6326 if (RefedProtocols.size() > 0) {
6327 Result += "\t(const struct _protocol_list_t *)&";
6328 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6329 Result += ClassName; Result += "_$_"; Result += CatName;
6330 Result += ",\n";
6331 }
6332 else
6333 Result += "\t0,\n";
6334
6335 if (ClassProperties.size() > 0) {
6336 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6337 Result += ClassName; Result += "_$_"; Result += CatName;
6338 Result += ",\n";
6339 }
6340 else
6341 Result += "\t0,\n";
6342
6343 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006344
6345 // Add static function to initialize the class pointer in the category structure.
6346 Result += "static void OBJC_CATEGORY_SETUP_$_";
6347 Result += ClassDecl->getNameAsString();
6348 Result += "_$_";
6349 Result += CatName;
6350 Result += "(void ) {\n";
6351 Result += "\t_OBJC_$_CATEGORY_";
6352 Result += ClassDecl->getNameAsString();
6353 Result += "_$_";
6354 Result += CatName;
6355 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6356 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006357}
6358
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006359static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6360 ASTContext *Context, std::string &Result,
6361 ArrayRef<ObjCMethodDecl *> Methods,
6362 StringRef VarName,
6363 StringRef ProtocolName) {
6364 if (Methods.size() == 0)
6365 return;
6366
6367 Result += "\nstatic const char *";
6368 Result += VarName; Result += ProtocolName;
6369 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6370 Result += "{\n";
6371 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6372 ObjCMethodDecl *MD = Methods[i];
6373 std::string MethodTypeString, QuoteMethodTypeString;
6374 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6375 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6376 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6377 if (i == e-1)
6378 Result += "\n};\n";
6379 else {
6380 Result += ",\n";
6381 }
6382 }
6383}
6384
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006385static void Write_IvarOffsetVar(ASTContext *Context,
6386 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006387 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006388 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006389 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6390 // this is what happens:
6391 /**
6392 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6393 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6394 Class->getVisibility() == HiddenVisibility)
6395 Visibility shoud be: HiddenVisibility;
6396 else
6397 Visibility shoud be: DefaultVisibility;
6398 */
6399
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006400 Result += "\n";
6401 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6402 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006403 if (Context->getLangOpts().MicrosoftExt)
6404 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6405
6406 if (!Context->getLangOpts().MicrosoftExt ||
6407 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006408 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006409 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006410 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006411 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006412 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006413 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6414 Result += " = ";
6415 if (IvarDecl->isBitField()) {
6416 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6417 // place all bitfields at offset 0.
6418 Result += "0;\n";
6419 }
6420 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006421 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006422 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006423 Result += "_IMPL, ";
6424 Result += IvarDecl->getName(); Result += ");\n";
6425 }
6426 }
6427}
6428
Fariborz Jahanianae932952012-02-10 20:47:10 +00006429static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6430 ASTContext *Context, std::string &Result,
6431 ArrayRef<ObjCIvarDecl *> Ivars,
6432 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006433 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006434 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006435 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006436
Fariborz Jahanianae932952012-02-10 20:47:10 +00006437 Result += "\nstatic ";
6438 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6439 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006440 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006441 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6442 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6443 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6444 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6445 ObjCIvarDecl *IvarDecl = Ivars[i];
6446 if (i == 0)
6447 Result += "\t{{";
6448 else
6449 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006450 Result += "(unsigned long int *)&";
6451 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006452 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006453
6454 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6455 std::string IvarTypeString, QuoteIvarTypeString;
6456 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6457 IvarDecl);
6458 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6459 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6460
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006461 // FIXME. this alignment represents the host alignment and need be changed to
6462 // represent the target alignment.
6463 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6464 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006465 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006466 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6467 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006468 if (i == e-1)
6469 Result += "}}\n";
6470 else
6471 Result += "},\n";
6472 }
6473 Result += "};\n";
6474 }
6475}
6476
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006477/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006478void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6479 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006480
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006481 // Do not synthesize the protocol more than once.
6482 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6483 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006484 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006485
6486 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6487 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006488 // Must write out all protocol definitions in current qualifier list,
6489 // and in their nested qualifiers before writing out current definition.
6490 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6491 E = PDecl->protocol_end(); I != E; ++I)
6492 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006493
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006494 // Construct method lists.
6495 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6496 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6497 for (ObjCProtocolDecl::instmeth_iterator
6498 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6499 I != E; ++I) {
6500 ObjCMethodDecl *MD = *I;
6501 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6502 OptInstanceMethods.push_back(MD);
6503 } else {
6504 InstanceMethods.push_back(MD);
6505 }
6506 }
6507
6508 for (ObjCProtocolDecl::classmeth_iterator
6509 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6510 I != E; ++I) {
6511 ObjCMethodDecl *MD = *I;
6512 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6513 OptClassMethods.push_back(MD);
6514 } else {
6515 ClassMethods.push_back(MD);
6516 }
6517 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006518 std::vector<ObjCMethodDecl *> AllMethods;
6519 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6520 AllMethods.push_back(InstanceMethods[i]);
6521 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6522 AllMethods.push_back(ClassMethods[i]);
6523 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6524 AllMethods.push_back(OptInstanceMethods[i]);
6525 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6526 AllMethods.push_back(OptClassMethods[i]);
6527
6528 Write__extendedMethodTypes_initializer(*this, Context, Result,
6529 AllMethods,
6530 "_OBJC_PROTOCOL_METHOD_TYPES_",
6531 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006532 // Protocol's super protocol list
6533 std::vector<ObjCProtocolDecl *> SuperProtocols;
6534 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6535 E = PDecl->protocol_end(); I != E; ++I)
6536 SuperProtocols.push_back(*I);
6537
6538 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6539 "_OBJC_PROTOCOL_REFS_",
6540 PDecl->getNameAsString());
6541
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006542 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006543 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006544 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006545
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006546 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006547 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006548 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006549
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006550 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006551 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006552 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006553
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006554 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006555 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006556 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006557
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006558 // Protocol's property metadata.
6559 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6560 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6561 E = PDecl->prop_end(); I != E; ++I)
6562 ProtocolProperties.push_back(*I);
6563
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006564 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006565 /* Container */0,
6566 "_OBJC_PROTOCOL_PROPERTIES_",
6567 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006568
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006569 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006570 Result += "\n";
6571 if (LangOpts.MicrosoftExt)
6572 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006573 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006574 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006575 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6576 Result += "\t0,\n"; // id is; is null
6577 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006578 if (SuperProtocols.size() > 0) {
6579 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6580 Result += PDecl->getNameAsString(); Result += ",\n";
6581 }
6582 else
6583 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006584 if (InstanceMethods.size() > 0) {
6585 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6586 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006587 }
6588 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006589 Result += "\t0,\n";
6590
6591 if (ClassMethods.size() > 0) {
6592 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6593 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006594 }
6595 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006596 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006597
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006598 if (OptInstanceMethods.size() > 0) {
6599 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6600 Result += PDecl->getNameAsString(); Result += ",\n";
6601 }
6602 else
6603 Result += "\t0,\n";
6604
6605 if (OptClassMethods.size() > 0) {
6606 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6607 Result += PDecl->getNameAsString(); Result += ",\n";
6608 }
6609 else
6610 Result += "\t0,\n";
6611
6612 if (ProtocolProperties.size() > 0) {
6613 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6614 Result += PDecl->getNameAsString(); Result += ",\n";
6615 }
6616 else
6617 Result += "\t0,\n";
6618
6619 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6620 Result += "\t0,\n";
6621
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006622 if (AllMethods.size() > 0) {
6623 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6624 Result += PDecl->getNameAsString();
6625 Result += "\n};\n";
6626 }
6627 else
6628 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006629
6630 // Use this protocol meta-data to build protocol list table in section
6631 // .objc_protolist$B
6632 // Unspecified visibility means 'private extern'.
6633 if (LangOpts.MicrosoftExt)
6634 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6635 Result += "struct _protocol_t *";
6636 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6637 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6638 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006639
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006640 // Mark this protocol as having been generated.
6641 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6642 llvm_unreachable("protocol already synthesized");
6643
6644}
6645
6646void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6647 const ObjCList<ObjCProtocolDecl> &Protocols,
6648 StringRef prefix, StringRef ClassName,
6649 std::string &Result) {
6650 if (Protocols.empty()) return;
6651
6652 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006653 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006654
6655 // Output the top lovel protocol meta-data for the class.
6656 /* struct _objc_protocol_list {
6657 struct _objc_protocol_list *next;
6658 int protocol_count;
6659 struct _objc_protocol *class_protocols[];
6660 }
6661 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006662 Result += "\n";
6663 if (LangOpts.MicrosoftExt)
6664 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6665 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006666 Result += "\tstruct _objc_protocol_list *next;\n";
6667 Result += "\tint protocol_count;\n";
6668 Result += "\tstruct _objc_protocol *class_protocols[";
6669 Result += utostr(Protocols.size());
6670 Result += "];\n} _OBJC_";
6671 Result += prefix;
6672 Result += "_PROTOCOLS_";
6673 Result += ClassName;
6674 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6675 "{\n\t0, ";
6676 Result += utostr(Protocols.size());
6677 Result += "\n";
6678
6679 Result += "\t,{&_OBJC_PROTOCOL_";
6680 Result += Protocols[0]->getNameAsString();
6681 Result += " \n";
6682
6683 for (unsigned i = 1; i != Protocols.size(); i++) {
6684 Result += "\t ,&_OBJC_PROTOCOL_";
6685 Result += Protocols[i]->getNameAsString();
6686 Result += "\n";
6687 }
6688 Result += "\t }\n};\n";
6689}
6690
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006691/// hasObjCExceptionAttribute - Return true if this class or any super
6692/// class has the __objc_exception__ attribute.
6693/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6694static bool hasObjCExceptionAttribute(ASTContext &Context,
6695 const ObjCInterfaceDecl *OID) {
6696 if (OID->hasAttr<ObjCExceptionAttr>())
6697 return true;
6698 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6699 return hasObjCExceptionAttribute(Context, Super);
6700 return false;
6701}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006702
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006703void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6704 std::string &Result) {
6705 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6706
6707 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006708 if (CDecl->isImplicitInterfaceDecl())
6709 assert(false &&
6710 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006711
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006712 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006713 SmallVector<ObjCIvarDecl *, 8> IVars;
6714
6715 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6716 IVD; IVD = IVD->getNextIvar()) {
6717 // Ignore unnamed bit-fields.
6718 if (!IVD->getDeclName())
6719 continue;
6720 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006721 }
6722
Fariborz Jahanianae932952012-02-10 20:47:10 +00006723 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006724 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006725 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006726
6727 // Build _objc_method_list for class's instance methods if needed
6728 SmallVector<ObjCMethodDecl *, 32>
6729 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6730
6731 // If any of our property implementations have associated getters or
6732 // setters, produce metadata for them as well.
6733 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6734 PropEnd = IDecl->propimpl_end();
6735 Prop != PropEnd; ++Prop) {
6736 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6737 continue;
6738 if (!(*Prop)->getPropertyIvarDecl())
6739 continue;
6740 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6741 if (!PD)
6742 continue;
6743 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6744 if (!Getter->isDefined())
6745 InstanceMethods.push_back(Getter);
6746 if (PD->isReadOnly())
6747 continue;
6748 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6749 if (!Setter->isDefined())
6750 InstanceMethods.push_back(Setter);
6751 }
6752
6753 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6754 "_OBJC_$_INSTANCE_METHODS_",
6755 IDecl->getNameAsString(), true);
6756
6757 SmallVector<ObjCMethodDecl *, 32>
6758 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6759
6760 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6761 "_OBJC_$_CLASS_METHODS_",
6762 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006763
6764 // Protocols referenced in class declaration?
6765 // Protocol's super protocol list
6766 std::vector<ObjCProtocolDecl *> RefedProtocols;
6767 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6768 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6769 E = Protocols.end();
6770 I != E; ++I) {
6771 RefedProtocols.push_back(*I);
6772 // Must write out all protocol definitions in current qualifier list,
6773 // and in their nested qualifiers before writing out current definition.
6774 RewriteObjCProtocolMetaData(*I, Result);
6775 }
6776
6777 Write_protocol_list_initializer(Context, Result,
6778 RefedProtocols,
6779 "_OBJC_CLASS_PROTOCOLS_$_",
6780 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006781
6782 // Protocol's property metadata.
6783 std::vector<ObjCPropertyDecl *> ClassProperties;
6784 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6785 E = CDecl->prop_end(); I != E; ++I)
6786 ClassProperties.push_back(*I);
6787
6788 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006789 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006790 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006791 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006792
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006793
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006794 // Data for initializing _class_ro_t metaclass meta-data
6795 uint32_t flags = CLS_META;
6796 std::string InstanceSize;
6797 std::string InstanceStart;
6798
6799
6800 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6801 if (classIsHidden)
6802 flags |= OBJC2_CLS_HIDDEN;
6803
6804 if (!CDecl->getSuperClass())
6805 // class is root
6806 flags |= CLS_ROOT;
6807 InstanceSize = "sizeof(struct _class_t)";
6808 InstanceStart = InstanceSize;
6809 Write__class_ro_t_initializer(Context, Result, flags,
6810 InstanceStart, InstanceSize,
6811 ClassMethods,
6812 0,
6813 0,
6814 0,
6815 "_OBJC_METACLASS_RO_$_",
6816 CDecl->getNameAsString());
6817
6818
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006819 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006820 flags = CLS;
6821 if (classIsHidden)
6822 flags |= OBJC2_CLS_HIDDEN;
6823
6824 if (hasObjCExceptionAttribute(*Context, CDecl))
6825 flags |= CLS_EXCEPTION;
6826
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006827 if (!CDecl->getSuperClass())
6828 // class is root
6829 flags |= CLS_ROOT;
6830
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006831 InstanceSize.clear();
6832 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006833 if (!ObjCSynthesizedStructs.count(CDecl)) {
6834 InstanceSize = "0";
6835 InstanceStart = "0";
6836 }
6837 else {
6838 InstanceSize = "sizeof(struct ";
6839 InstanceSize += CDecl->getNameAsString();
6840 InstanceSize += "_IMPL)";
6841
6842 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6843 if (IVD) {
6844 InstanceStart += "__OFFSETOFIVAR__(struct ";
6845 InstanceStart += CDecl->getNameAsString();
6846 InstanceStart += "_IMPL, ";
6847 InstanceStart += IVD->getNameAsString();
6848 InstanceStart += ")";
6849 }
6850 else
6851 InstanceStart = InstanceSize;
6852 }
6853 Write__class_ro_t_initializer(Context, Result, flags,
6854 InstanceStart, InstanceSize,
6855 InstanceMethods,
6856 RefedProtocols,
6857 IVars,
6858 ClassProperties,
6859 "_OBJC_CLASS_RO_$_",
6860 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006861
6862 Write_class_t(Context, Result,
6863 "OBJC_METACLASS_$_",
6864 CDecl, /*metaclass*/true);
6865
6866 Write_class_t(Context, Result,
6867 "OBJC_CLASS_$_",
6868 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006869
6870 if (ImplementationIsNonLazy(IDecl))
6871 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006872
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006873}
6874
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006875void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6876 int ClsDefCount = ClassImplementation.size();
6877 if (!ClsDefCount)
6878 return;
6879 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6880 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6881 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6882 for (int i = 0; i < ClsDefCount; i++) {
6883 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6884 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6885 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6886 Result += CDecl->getName(); Result += ",\n";
6887 }
6888 Result += "};\n";
6889}
6890
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006891void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6892 int ClsDefCount = ClassImplementation.size();
6893 int CatDefCount = CategoryImplementation.size();
6894
6895 // For each implemented class, write out all its meta data.
6896 for (int i = 0; i < ClsDefCount; i++)
6897 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6898
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006899 RewriteClassSetupInitHook(Result);
6900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006901 // For each implemented category, write out all its meta data.
6902 for (int i = 0; i < CatDefCount; i++)
6903 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6904
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006905 RewriteCategorySetupInitHook(Result);
6906
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006907 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006908 if (LangOpts.MicrosoftExt)
6909 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006910 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6911 Result += llvm::utostr(ClsDefCount); Result += "]";
6912 Result +=
6913 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6914 "regular,no_dead_strip\")))= {\n";
6915 for (int i = 0; i < ClsDefCount; i++) {
6916 Result += "\t&OBJC_CLASS_$_";
6917 Result += ClassImplementation[i]->getNameAsString();
6918 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006919 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006920 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006921
6922 if (!DefinedNonLazyClasses.empty()) {
6923 if (LangOpts.MicrosoftExt)
6924 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6925 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6926 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6927 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6928 Result += ",\n";
6929 }
6930 Result += "};\n";
6931 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006932 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006933
6934 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006935 if (LangOpts.MicrosoftExt)
6936 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006937 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6938 Result += llvm::utostr(CatDefCount); Result += "]";
6939 Result +=
6940 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6941 "regular,no_dead_strip\")))= {\n";
6942 for (int i = 0; i < CatDefCount; i++) {
6943 Result += "\t&_OBJC_$_CATEGORY_";
6944 Result +=
6945 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6946 Result += "_$_";
6947 Result += CategoryImplementation[i]->getNameAsString();
6948 Result += ",\n";
6949 }
6950 Result += "};\n";
6951 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006952
6953 if (!DefinedNonLazyCategories.empty()) {
6954 if (LangOpts.MicrosoftExt)
6955 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6956 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6957 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6958 Result += "\t&_OBJC_$_CATEGORY_";
6959 Result +=
6960 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6961 Result += "_$_";
6962 Result += DefinedNonLazyCategories[i]->getNameAsString();
6963 Result += ",\n";
6964 }
6965 Result += "};\n";
6966 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006967}
6968
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006969void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6970 if (LangOpts.MicrosoftExt)
6971 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6972
6973 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6974 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006975 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006976}
6977
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006978/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6979/// implementation.
6980void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6981 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006982 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006983 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6984 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006985 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006986 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6987 CDecl = CDecl->getNextClassCategory())
6988 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6989 break;
6990
6991 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006992 FullCategoryName += "_$_";
6993 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006994
6995 // Build _objc_method_list for class's instance methods if needed
6996 SmallVector<ObjCMethodDecl *, 32>
6997 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6998
6999 // If any of our property implementations have associated getters or
7000 // setters, produce metadata for them as well.
7001 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7002 PropEnd = IDecl->propimpl_end();
7003 Prop != PropEnd; ++Prop) {
7004 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7005 continue;
7006 if (!(*Prop)->getPropertyIvarDecl())
7007 continue;
7008 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7009 if (!PD)
7010 continue;
7011 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7012 InstanceMethods.push_back(Getter);
7013 if (PD->isReadOnly())
7014 continue;
7015 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7016 InstanceMethods.push_back(Setter);
7017 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007018
Fariborz Jahanian61186122012-02-17 18:40:41 +00007019 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7020 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7021 FullCategoryName, true);
7022
7023 SmallVector<ObjCMethodDecl *, 32>
7024 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7025
7026 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7027 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7028 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007029
7030 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007031 // Protocol's super protocol list
7032 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007033 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7034 E = CDecl->protocol_end();
7035
7036 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007037 RefedProtocols.push_back(*I);
7038 // Must write out all protocol definitions in current qualifier list,
7039 // and in their nested qualifiers before writing out current definition.
7040 RewriteObjCProtocolMetaData(*I, Result);
7041 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007042
Fariborz Jahanian61186122012-02-17 18:40:41 +00007043 Write_protocol_list_initializer(Context, Result,
7044 RefedProtocols,
7045 "_OBJC_CATEGORY_PROTOCOLS_$_",
7046 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007047
Fariborz Jahanian61186122012-02-17 18:40:41 +00007048 // Protocol's property metadata.
7049 std::vector<ObjCPropertyDecl *> ClassProperties;
7050 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7051 E = CDecl->prop_end(); I != E; ++I)
7052 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007053
Fariborz Jahanian61186122012-02-17 18:40:41 +00007054 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7055 /* Container */0,
7056 "_OBJC_$_PROP_LIST_",
7057 FullCategoryName);
7058
7059 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007060 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007061 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007062 InstanceMethods,
7063 ClassMethods,
7064 RefedProtocols,
7065 ClassProperties);
7066
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007067 // Determine if this category is also "non-lazy".
7068 if (ImplementationIsNonLazy(IDecl))
7069 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007070
7071}
7072
7073void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7074 int CatDefCount = CategoryImplementation.size();
7075 if (!CatDefCount)
7076 return;
7077 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7078 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7079 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7080 for (int i = 0; i < CatDefCount; i++) {
7081 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7082 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7083 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7084 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7085 Result += ClassDecl->getName();
7086 Result += "_$_";
7087 Result += CatDecl->getName();
7088 Result += ",\n";
7089 }
7090 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007091}
7092
7093// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7094/// class methods.
7095template<typename MethodIterator>
7096void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7097 MethodIterator MethodEnd,
7098 bool IsInstanceMethod,
7099 StringRef prefix,
7100 StringRef ClassName,
7101 std::string &Result) {
7102 if (MethodBegin == MethodEnd) return;
7103
7104 if (!objc_impl_method) {
7105 /* struct _objc_method {
7106 SEL _cmd;
7107 char *method_types;
7108 void *_imp;
7109 }
7110 */
7111 Result += "\nstruct _objc_method {\n";
7112 Result += "\tSEL _cmd;\n";
7113 Result += "\tchar *method_types;\n";
7114 Result += "\tvoid *_imp;\n";
7115 Result += "};\n";
7116
7117 objc_impl_method = true;
7118 }
7119
7120 // Build _objc_method_list for class's methods if needed
7121
7122 /* struct {
7123 struct _objc_method_list *next_method;
7124 int method_count;
7125 struct _objc_method method_list[];
7126 }
7127 */
7128 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007129 Result += "\n";
7130 if (LangOpts.MicrosoftExt) {
7131 if (IsInstanceMethod)
7132 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7133 else
7134 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7135 }
7136 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007137 Result += "\tstruct _objc_method_list *next_method;\n";
7138 Result += "\tint method_count;\n";
7139 Result += "\tstruct _objc_method method_list[";
7140 Result += utostr(NumMethods);
7141 Result += "];\n} _OBJC_";
7142 Result += prefix;
7143 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7144 Result += "_METHODS_";
7145 Result += ClassName;
7146 Result += " __attribute__ ((used, section (\"__OBJC, __";
7147 Result += IsInstanceMethod ? "inst" : "cls";
7148 Result += "_meth\")))= ";
7149 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7150
7151 Result += "\t,{{(SEL)\"";
7152 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7153 std::string MethodTypeString;
7154 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7155 Result += "\", \"";
7156 Result += MethodTypeString;
7157 Result += "\", (void *)";
7158 Result += MethodInternalNames[*MethodBegin];
7159 Result += "}\n";
7160 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7161 Result += "\t ,{(SEL)\"";
7162 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7163 std::string MethodTypeString;
7164 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7165 Result += "\", \"";
7166 Result += MethodTypeString;
7167 Result += "\", (void *)";
7168 Result += MethodInternalNames[*MethodBegin];
7169 Result += "}\n";
7170 }
7171 Result += "\t }\n};\n";
7172}
7173
7174Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7175 SourceRange OldRange = IV->getSourceRange();
7176 Expr *BaseExpr = IV->getBase();
7177
7178 // Rewrite the base, but without actually doing replaces.
7179 {
7180 DisableReplaceStmtScope S(*this);
7181 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7182 IV->setBase(BaseExpr);
7183 }
7184
7185 ObjCIvarDecl *D = IV->getDecl();
7186
7187 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007188
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007189 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7190 const ObjCInterfaceType *iFaceDecl =
7191 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7192 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7193 // lookup which class implements the instance variable.
7194 ObjCInterfaceDecl *clsDeclared = 0;
7195 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7196 clsDeclared);
7197 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7198
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007199 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007200 std::string IvarOffsetName;
7201 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7202
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007203 ReferencedIvars[clsDeclared].insert(D);
7204
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007205 // cast offset to "char *".
7206 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7207 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007208 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007209 BaseExpr);
7210 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7211 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7212 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007213 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7214 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007215 SourceLocation());
7216 BinaryOperator *addExpr =
7217 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7218 Context->getPointerType(Context->CharTy),
7219 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007220 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007221 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7222 SourceLocation(),
7223 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007224 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007225 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007226 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007227
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007228 castExpr = NoTypeInfoCStyleCastExpr(Context,
7229 castT,
7230 CK_BitCast,
7231 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007232 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007233 VK_LValue, OK_Ordinary,
7234 SourceLocation());
7235 PE = new (Context) ParenExpr(OldRange.getBegin(),
7236 OldRange.getEnd(),
7237 Exp);
7238
7239 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007240 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007241
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007242 ReplaceStmtWithRange(IV, Replacement, OldRange);
7243 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007244}