blob: a248675d771cb597881cf0b575723d364af485ca [file] [log] [blame]
Fariborz Jahanian11671902012-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
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121
Fariborz Jahanian11671902012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000133
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000136
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000157
Fariborz Jahanian11671902012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000187 // Top Level Driver code.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000224
225 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
226 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
227 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
228 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
229 RewriteBlockPointerDecl(TD);
230 else if (TD->getUnderlyingType()->isFunctionPointerType())
231 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
232 else
233 RewriteObjCQualifiedInterfaceTypes(TD);
234 }
235 }
236 return;
237 }
238
Fariborz Jahanian11671902012-02-07 17:11:38 +0000239 void HandleTopLevelSingleDecl(Decl *D);
240 void HandleDeclInMainFile(Decl *D);
241 RewriteModernObjC(std::string inFile, raw_ostream *OS,
242 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000243 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000244
245 ~RewriteModernObjC() {}
246
247 virtual void HandleTranslationUnit(ASTContext &C);
248
249 void ReplaceStmt(Stmt *Old, Stmt *New) {
250 Stmt *ReplacingStmt = ReplacedNodes[Old];
251
252 if (ReplacingStmt)
253 return; // We can't rewrite the same node twice.
254
255 if (DisableReplaceStmt)
256 return;
257
258 // If replacement succeeded or warning disabled return with no warning.
259 if (!Rewrite.ReplaceStmt(Old, New)) {
260 ReplacedNodes[Old] = New;
261 return;
262 }
263 if (SilenceRewriteMacroWarning)
264 return;
265 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
266 << Old->getSourceRange();
267 }
268
269 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
270 if (DisableReplaceStmt)
271 return;
272
273 // Measure the old text.
274 int Size = Rewrite.getRangeSize(SrcRange);
275 if (Size == -1) {
276 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
277 << Old->getSourceRange();
278 return;
279 }
280 // Get the new text.
281 std::string SStr;
282 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000283 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000284 const std::string &Str = S.str();
285
286 // If replacement succeeded or warning disabled return with no warning.
287 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
288 ReplacedNodes[Old] = New;
289 return;
290 }
291 if (SilenceRewriteMacroWarning)
292 return;
293 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
294 << Old->getSourceRange();
295 }
296
297 void InsertText(SourceLocation Loc, StringRef Str,
298 bool InsertAfter = true) {
299 // If insertion succeeded or warning disabled return with no warning.
300 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
301 SilenceRewriteMacroWarning)
302 return;
303
304 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
305 }
306
307 void ReplaceText(SourceLocation Start, unsigned OrigLength,
308 StringRef Str) {
309 // If removal succeeded or warning disabled return with no warning.
310 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
311 SilenceRewriteMacroWarning)
312 return;
313
314 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
315 }
316
317 // Syntactic Rewriting.
318 void RewriteRecordBody(RecordDecl *RD);
319 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000320 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000321 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
322 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000323 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000324 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000325 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
326 const std::string &typedefString);
327 void RewriteImplementations();
328 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
329 ObjCImplementationDecl *IMD,
330 ObjCCategoryImplDecl *CID);
331 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
332 void RewriteImplementationDecl(Decl *Dcl);
333 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
334 ObjCMethodDecl *MDecl, std::string &ResultStr);
335 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
336 const FunctionType *&FPRetType);
337 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
338 ValueDecl *VD, bool def=false);
339 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
340 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
341 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000342 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000343 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
344 void RewriteProperty(ObjCPropertyDecl *prop);
345 void RewriteFunctionDecl(FunctionDecl *FD);
346 void RewriteBlockPointerType(std::string& Str, QualType Type);
347 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000348 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000349 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
350 void RewriteTypeOfDecl(VarDecl *VD);
351 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000352
353 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000354
355 // Expression Rewriting.
356 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
357 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
358 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
359 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
360 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
361 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
362 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000363 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000364 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000365 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000366 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000367 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000368 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000369 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
371 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
372 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
373 SourceLocation OrigEnd);
374 Stmt *RewriteBreakStmt(BreakStmt *S);
375 Stmt *RewriteContinueStmt(ContinueStmt *S);
376 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000377 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000378 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000379
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000380 // Computes ivar bitfield group no.
381 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
382 // Names field decl. for ivar bitfield group.
383 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
384 // Names struct type for ivar bitfield group.
385 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
386 // Names symbol for ivar bitfield group field offset.
387 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
388 // Given an ivar bitfield, it builds (or finds) its group record type.
389 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
390 QualType SynthesizeBitfieldGroupStructType(
391 ObjCIvarDecl *IV,
392 SmallVectorImpl<ObjCIvarDecl *> &IVars);
393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 // Block rewriting.
395 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
396
397 // Block specific rewrite rules.
398 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000399 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000400 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000401 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
402 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
403
404 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
405 std::string &Result);
406
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000407 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000408 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000409 bool &IsNamedDefinition);
410 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
411 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000412
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000413 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
414
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000415 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
416 std::string &Result);
417
Fariborz Jahanian11671902012-02-07 17:11:38 +0000418 virtual void Initialize(ASTContext &context);
419
Benjamin Kramer474261a2012-06-02 10:20:41 +0000420 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000421 // rewriting routines on the new ASTs.
422 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
423 Expr **args, unsigned nargs,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000426
427 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000428 QualType returnType,
429 SmallVectorImpl<QualType> &ArgTypes,
430 SmallVectorImpl<Expr*> &MsgExprs,
431 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000432
433 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
434 SourceLocation StartLoc=SourceLocation(),
435 SourceLocation EndLoc=SourceLocation());
436
437 void SynthCountByEnumWithState(std::string &buf);
438 void SynthMsgSendFunctionDecl();
439 void SynthMsgSendSuperFunctionDecl();
440 void SynthMsgSendStretFunctionDecl();
441 void SynthMsgSendFpretFunctionDecl();
442 void SynthMsgSendSuperStretFunctionDecl();
443 void SynthGetClassFunctionDecl();
444 void SynthGetMetaClassFunctionDecl();
445 void SynthGetSuperClassFunctionDecl();
446 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000447 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000448
449 // Rewriting metadata
450 template<typename MethodIterator>
451 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
452 MethodIterator MethodEnd,
453 bool IsInstanceMethod,
454 StringRef prefix,
455 StringRef ClassName,
456 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000457 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
458 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000459 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 const ObjCList<ObjCProtocolDecl> &Prots,
461 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000464 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000465
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000466 void RewriteMetaDataIntoBuffer(std::string &Result);
467 void WriteImageInfo(std::string &Result);
468 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000469 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000470 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471
472 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000473 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000475 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000476
477
478 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
479 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
480 StringRef funcName, std::string Tag);
481 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
482 StringRef funcName, std::string Tag);
483 std::string SynthesizeBlockImpl(BlockExpr *CE,
484 std::string Tag, std::string Desc);
485 std::string SynthesizeBlockDescriptor(std::string DescTag,
486 std::string ImplTag,
487 int i, StringRef funcName,
488 unsigned hasCopy);
489 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
490 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
491 StringRef FunName);
492 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
493 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000494 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000495
496 // Misc. helper routines.
497 QualType getProtocolType();
498 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000499 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
500 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
501 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
502
503 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
504 void CollectBlockDeclRefInfo(BlockExpr *Exp);
505 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000506 void GetInnerBlockDeclRefExprs(Stmt *S,
507 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000508 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
509
510 // We avoid calling Type::isBlockPointerType(), since it operates on the
511 // canonical type. We only care if the top-level type is a closure pointer.
512 bool isTopLevelBlockPointerType(QualType T) {
513 return isa<BlockPointerType>(T);
514 }
515
516 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
517 /// to a function pointer type and upon success, returns true; false
518 /// otherwise.
519 bool convertBlockPointerToFunctionPointer(QualType &T) {
520 if (isTopLevelBlockPointerType(T)) {
521 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
522 T = Context->getPointerType(BPT->getPointeeType());
523 return true;
524 }
525 return false;
526 }
527
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000528 bool convertObjCTypeToCStyleType(QualType &T);
529
Fariborz Jahanian11671902012-02-07 17:11:38 +0000530 bool needToScanForQualifiers(QualType T);
531 QualType getSuperStructType();
532 QualType getConstantStringStructType();
533 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
534 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
535
536 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000537 if (T->isObjCQualifiedIdType()) {
538 bool isConst = T.isConstQualified();
539 T = isConst ? Context->getObjCIdType().withConst()
540 : Context->getObjCIdType();
541 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000542 else if (T->isObjCQualifiedClassType())
543 T = Context->getObjCClassType();
544 else if (T->isObjCObjectPointerType() &&
545 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
546 if (const ObjCObjectPointerType * OBJPT =
547 T->getAsObjCInterfacePointerType()) {
548 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
549 T = QualType(IFaceT, 0);
550 T = Context->getPointerType(T);
551 }
552 }
553 }
554
555 // FIXME: This predicate seems like it would be useful to add to ASTContext.
556 bool isObjCType(QualType T) {
557 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
558 return false;
559
560 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
561
562 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
563 OCT == Context->getCanonicalType(Context->getObjCClassType()))
564 return true;
565
566 if (const PointerType *PT = OCT->getAs<PointerType>()) {
567 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
568 PT->getPointeeType()->isObjCQualifiedIdType())
569 return true;
570 }
571 return false;
572 }
573 bool PointerTypeTakesAnyBlockArguments(QualType QT);
574 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
575 void GetExtentOfArgList(const char *Name, const char *&LParen,
576 const char *&RParen);
577
578 void QuoteDoublequotes(std::string &From, std::string &To) {
579 for (unsigned i = 0; i < From.length(); i++) {
580 if (From[i] == '"')
581 To += "\\\"";
582 else
583 To += From[i];
584 }
585 }
586
587 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000588 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000589 bool variadic = false) {
590 if (result == Context->getObjCInstanceType())
591 result = Context->getObjCIdType();
592 FunctionProtoType::ExtProtoInfo fpi;
593 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000594 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
596
597 // Helper function: create a CStyleCastExpr with trivial type source info.
598 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
599 CastKind Kind, Expr *E) {
600 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
601 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
602 SourceLocation(), SourceLocation());
603 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000604
605 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
606 IdentifierInfo* II = &Context->Idents.get("load");
607 Selector LoadSel = Context->Selectors.getSelector(0, &II);
608 return OD->getClassMethod(LoadSel) != 0;
609 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000610 };
611
612}
613
614void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
615 NamedDecl *D) {
616 if (const FunctionProtoType *fproto
617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
618 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
619 E = fproto->arg_type_end(); I && (I != E); ++I)
620 if (isTopLevelBlockPointerType(*I)) {
621 // All the args are checked/rewritten. Don't call twice!
622 RewriteBlockPointerDecl(D);
623 break;
624 }
625 }
626}
627
628void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
629 const PointerType *PT = funcType->getAs<PointerType>();
630 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
631 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
632}
633
634static bool IsHeaderFile(const std::string &Filename) {
635 std::string::size_type DotPos = Filename.rfind('.');
636
637 if (DotPos == std::string::npos) {
638 // no file extension
639 return false;
640 }
641
642 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
643 // C header: .h
644 // C++ header: .hh or .H;
645 return Ext == "h" || Ext == "hh" || Ext == "H";
646}
647
648RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
649 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000650 bool silenceMacroWarn,
651 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000652 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000653 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000654 IsHeader = IsHeaderFile(inFile);
655 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
656 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000657 // FIXME. This should be an error. But if block is not called, it is OK. And it
658 // may break including some headers.
659 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
660 "rewriting block literal declared in global scope is not implemented");
661
Fariborz Jahanian11671902012-02-07 17:11:38 +0000662 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
663 DiagnosticsEngine::Warning,
664 "rewriter doesn't support user-specified control flow semantics "
665 "for @try/@finally (code may not execute properly)");
666}
667
668ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
669 raw_ostream* OS,
670 DiagnosticsEngine &Diags,
671 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000672 bool SilenceRewriteMacroWarning,
673 bool LineInfo) {
674 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
675 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000676}
677
678void RewriteModernObjC::InitializeCommon(ASTContext &context) {
679 Context = &context;
680 SM = &Context->getSourceManager();
681 TUDecl = Context->getTranslationUnitDecl();
682 MsgSendFunctionDecl = 0;
683 MsgSendSuperFunctionDecl = 0;
684 MsgSendStretFunctionDecl = 0;
685 MsgSendSuperStretFunctionDecl = 0;
686 MsgSendFpretFunctionDecl = 0;
687 GetClassFunctionDecl = 0;
688 GetMetaClassFunctionDecl = 0;
689 GetSuperClassFunctionDecl = 0;
690 SelGetUidFunctionDecl = 0;
691 CFStringFunctionDecl = 0;
692 ConstantStringClassReference = 0;
693 NSStringRecord = 0;
694 CurMethodDef = 0;
695 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000696 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000697 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000698 SuperStructDecl = 0;
699 ProtocolTypeDecl = 0;
700 ConstantStringDecl = 0;
701 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000702 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000703 NumObjCStringLiterals = 0;
704 PropParentMap = 0;
705 CurrentBody = 0;
706 DisableReplaceStmt = false;
707 objc_impl_method = false;
708
709 // Get the ID and start/end of the main file.
710 MainFileID = SM->getMainFileID();
711 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
712 MainFileStart = MainBuf->getBufferStart();
713 MainFileEnd = MainBuf->getBufferEnd();
714
David Blaikiebbafb8a2012-03-11 07:00:24 +0000715 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000716}
717
718//===----------------------------------------------------------------------===//
719// Top Level Driver Code
720//===----------------------------------------------------------------------===//
721
722void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
723 if (Diags.hasErrorOccurred())
724 return;
725
726 // Two cases: either the decl could be in the main file, or it could be in a
727 // #included file. If the former, rewrite it now. If the later, check to see
728 // if we rewrote the #include/#import.
729 SourceLocation Loc = D->getLocation();
730 Loc = SM->getExpansionLoc(Loc);
731
732 // If this is for a builtin, ignore it.
733 if (Loc.isInvalid()) return;
734
735 // Look for built-in declarations that we need to refer during the rewrite.
736 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
737 RewriteFunctionDecl(FD);
738 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
739 // declared in <Foundation/NSString.h>
740 if (FVD->getName() == "_NSConstantStringClassReference") {
741 ConstantStringClassReference = FVD;
742 return;
743 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000744 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
745 RewriteCategoryDecl(CD);
746 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
747 if (PD->isThisDeclarationADefinition())
748 RewriteProtocolDecl(PD);
749 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000750 // FIXME. This will not work in all situations and leaving it out
751 // is harmless.
752 // RewriteLinkageSpec(LSD);
753
Fariborz Jahanian11671902012-02-07 17:11:38 +0000754 // Recurse into linkage specifications
755 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
756 DIEnd = LSD->decls_end();
757 DI != DIEnd; ) {
758 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
759 if (!IFace->isThisDeclarationADefinition()) {
760 SmallVector<Decl *, 8> DG;
761 SourceLocation StartLoc = IFace->getLocStart();
762 do {
763 if (isa<ObjCInterfaceDecl>(*DI) &&
764 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
765 StartLoc == (*DI)->getLocStart())
766 DG.push_back(*DI);
767 else
768 break;
769
770 ++DI;
771 } while (DI != DIEnd);
772 RewriteForwardClassDecl(DG);
773 continue;
774 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000775 else {
776 // Keep track of all interface declarations seen.
777 ObjCInterfacesSeen.push_back(IFace);
778 ++DI;
779 continue;
780 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000781 }
782
783 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
784 if (!Proto->isThisDeclarationADefinition()) {
785 SmallVector<Decl *, 8> DG;
786 SourceLocation StartLoc = Proto->getLocStart();
787 do {
788 if (isa<ObjCProtocolDecl>(*DI) &&
789 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
790 StartLoc == (*DI)->getLocStart())
791 DG.push_back(*DI);
792 else
793 break;
794
795 ++DI;
796 } while (DI != DIEnd);
797 RewriteForwardProtocolDecl(DG);
798 continue;
799 }
800 }
801
802 HandleTopLevelSingleDecl(*DI);
803 ++DI;
804 }
805 }
806 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000807 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000808 return HandleDeclInMainFile(D);
809}
810
811//===----------------------------------------------------------------------===//
812// Syntactic (non-AST) Rewriting Code
813//===----------------------------------------------------------------------===//
814
815void RewriteModernObjC::RewriteInclude() {
816 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
817 StringRef MainBuf = SM->getBufferData(MainFileID);
818 const char *MainBufStart = MainBuf.begin();
819 const char *MainBufEnd = MainBuf.end();
820 size_t ImportLen = strlen("import");
821
822 // Loop over the whole file, looking for includes.
823 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
824 if (*BufPtr == '#') {
825 if (++BufPtr == MainBufEnd)
826 return;
827 while (*BufPtr == ' ' || *BufPtr == '\t')
828 if (++BufPtr == MainBufEnd)
829 return;
830 if (!strncmp(BufPtr, "import", ImportLen)) {
831 // replace import with include
832 SourceLocation ImportLoc =
833 LocStart.getLocWithOffset(BufPtr-MainBufStart);
834 ReplaceText(ImportLoc, ImportLen, "include");
835 BufPtr += ImportLen;
836 }
837 }
838 }
839}
840
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000841static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
842 ObjCIvarDecl *IvarDecl, std::string &Result) {
843 Result += "OBJC_IVAR_$_";
844 Result += IDecl->getName();
845 Result += "$";
846 Result += IvarDecl->getName();
847}
848
849std::string
850RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
851 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
852
853 // Build name of symbol holding ivar offset.
854 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000855 if (D->isBitField())
856 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
857 else
858 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000859
860
861 std::string S = "(*(";
862 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000863 if (D->isBitField())
864 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000865
866 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
867 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
868 RD = RD->getDefinition();
869 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
870 // decltype(((Foo_IMPL*)0)->bar) *
871 ObjCContainerDecl *CDecl =
872 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
873 // ivar in class extensions requires special treatment.
874 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
875 CDecl = CatDecl->getClassInterface();
876 std::string RecName = CDecl->getName();
877 RecName += "_IMPL";
878 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
879 SourceLocation(), SourceLocation(),
880 &Context->Idents.get(RecName.c_str()));
881 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
882 unsigned UnsignedIntSize =
883 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
884 Expr *Zero = IntegerLiteral::Create(*Context,
885 llvm::APInt(UnsignedIntSize, 0),
886 Context->UnsignedIntTy, SourceLocation());
887 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
888 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
889 Zero);
890 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
891 SourceLocation(),
892 &Context->Idents.get(D->getNameAsString()),
893 IvarT, 0,
894 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000895 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000896 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
897 FD->getType(), VK_LValue,
898 OK_Ordinary);
899 IvarT = Context->getDecltypeType(ME, ME->getType());
900 }
901 }
902 convertObjCTypeToCStyleType(IvarT);
903 QualType castT = Context->getPointerType(IvarT);
904 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
905 S += TypeString;
906 S += ")";
907
908 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
909 S += "((char *)self + ";
910 S += IvarOffsetName;
911 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000912 if (D->isBitField()) {
913 S += ".";
914 S += D->getNameAsString();
915 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000916 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000917 return S;
918}
919
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000920/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
921/// been found in the class implementation. In this case, it must be synthesized.
922static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
923 ObjCPropertyDecl *PD,
924 bool getter) {
925 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
926 : !IMP->getInstanceMethod(PD->getSetterName());
927
928}
929
Fariborz Jahanian11671902012-02-07 17:11:38 +0000930void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
931 ObjCImplementationDecl *IMD,
932 ObjCCategoryImplDecl *CID) {
933 static bool objcGetPropertyDefined = false;
934 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000935 SourceLocation startGetterSetterLoc;
936
937 if (PID->getLocStart().isValid()) {
938 SourceLocation startLoc = PID->getLocStart();
939 InsertText(startLoc, "// ");
940 const char *startBuf = SM->getCharacterData(startLoc);
941 assert((*startBuf == '@') && "bogus @synthesize location");
942 const char *semiBuf = strchr(startBuf, ';');
943 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
944 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
945 }
946 else
947 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000948
949 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
950 return; // FIXME: is this correct?
951
952 // Generate the 'getter' function.
953 ObjCPropertyDecl *PD = PID->getPropertyDecl();
954 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000955 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000956
Bill Wendling44426052012-12-20 19:22:21 +0000957 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000958 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000959 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
960 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000961 ObjCPropertyDecl::OBJC_PR_copy));
962 std::string Getr;
963 if (GenGetProperty && !objcGetPropertyDefined) {
964 objcGetPropertyDefined = true;
965 // FIXME. Is this attribute correct in all cases?
966 Getr = "\nextern \"C\" __declspec(dllimport) "
967 "id objc_getProperty(id, SEL, long, bool);\n";
968 }
969 RewriteObjCMethodDecl(OID->getContainingInterface(),
970 PD->getGetterMethodDecl(), Getr);
971 Getr += "{ ";
972 // Synthesize an explicit cast to gain access to the ivar.
973 // See objc-act.c:objc_synthesize_new_getter() for details.
974 if (GenGetProperty) {
975 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
976 Getr += "typedef ";
977 const FunctionType *FPRetType = 0;
978 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
979 FPRetType);
980 Getr += " _TYPE";
981 if (FPRetType) {
982 Getr += ")"; // close the precedence "scope" for "*".
983
984 // Now, emit the argument types (if any).
985 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
986 Getr += "(";
987 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
988 if (i) Getr += ", ";
989 std::string ParamStr = FT->getArgType(i).getAsString(
990 Context->getPrintingPolicy());
991 Getr += ParamStr;
992 }
993 if (FT->isVariadic()) {
994 if (FT->getNumArgs()) Getr += ", ";
995 Getr += "...";
996 }
997 Getr += ")";
998 } else
999 Getr += "()";
1000 }
1001 Getr += ";\n";
1002 Getr += "return (_TYPE)";
1003 Getr += "objc_getProperty(self, _cmd, ";
1004 RewriteIvarOffsetComputation(OID, Getr);
1005 Getr += ", 1)";
1006 }
1007 else
1008 Getr += "return " + getIvarAccessString(OID);
1009 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001010 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001011 }
1012
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001013 if (PD->isReadOnly() ||
1014 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001015 return;
1016
1017 // Generate the 'setter' function.
1018 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001019 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001020 ObjCPropertyDecl::OBJC_PR_copy);
1021 if (GenSetProperty && !objcSetPropertyDefined) {
1022 objcSetPropertyDefined = true;
1023 // FIXME. Is this attribute correct in all cases?
1024 Setr = "\nextern \"C\" __declspec(dllimport) "
1025 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1026 }
1027
1028 RewriteObjCMethodDecl(OID->getContainingInterface(),
1029 PD->getSetterMethodDecl(), Setr);
1030 Setr += "{ ";
1031 // Synthesize an explicit cast to initialize the ivar.
1032 // See objc-act.c:objc_synthesize_new_setter() for details.
1033 if (GenSetProperty) {
1034 Setr += "objc_setProperty (self, _cmd, ";
1035 RewriteIvarOffsetComputation(OID, Setr);
1036 Setr += ", (id)";
1037 Setr += PD->getName();
1038 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001039 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001040 Setr += "0, ";
1041 else
1042 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001043 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001044 Setr += "1)";
1045 else
1046 Setr += "0)";
1047 }
1048 else {
1049 Setr += getIvarAccessString(OID) + " = ";
1050 Setr += PD->getName();
1051 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001052 Setr += "; }\n";
1053 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001054}
1055
1056static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1057 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001058 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001059 typedefString += ForwardDecl->getNameAsString();
1060 typedefString += "\n";
1061 typedefString += "#define _REWRITER_typedef_";
1062 typedefString += ForwardDecl->getNameAsString();
1063 typedefString += "\n";
1064 typedefString += "typedef struct objc_object ";
1065 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001066 // typedef struct { } _objc_exc_Classname;
1067 typedefString += ";\ntypedef struct {} _objc_exc_";
1068 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001069 typedefString += ";\n#endif\n";
1070}
1071
1072void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1073 const std::string &typedefString) {
1074 SourceLocation startLoc = ClassDecl->getLocStart();
1075 const char *startBuf = SM->getCharacterData(startLoc);
1076 const char *semiPtr = strchr(startBuf, ';');
1077 // Replace the @class with typedefs corresponding to the classes.
1078 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1079}
1080
1081void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1082 std::string typedefString;
1083 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001084 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1085 if (I == D.begin()) {
1086 // Translate to typedef's that forward reference structs with the same name
1087 // as the class. As a convenience, we include the original declaration
1088 // as a comment.
1089 typedefString += "// @class ";
1090 typedefString += ForwardDecl->getNameAsString();
1091 typedefString += ";";
1092 }
1093 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001094 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001095 else
1096 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001097 }
1098 DeclGroupRef::iterator I = D.begin();
1099 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1100}
1101
1102void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001103 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001104 std::string typedefString;
1105 for (unsigned i = 0; i < D.size(); i++) {
1106 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1107 if (i == 0) {
1108 typedefString += "// @class ";
1109 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001110 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001111 }
1112 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1113 }
1114 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1115}
1116
1117void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1118 // When method is a synthesized one, such as a getter/setter there is
1119 // nothing to rewrite.
1120 if (Method->isImplicit())
1121 return;
1122 SourceLocation LocStart = Method->getLocStart();
1123 SourceLocation LocEnd = Method->getLocEnd();
1124
1125 if (SM->getExpansionLineNumber(LocEnd) >
1126 SM->getExpansionLineNumber(LocStart)) {
1127 InsertText(LocStart, "#if 0\n");
1128 ReplaceText(LocEnd, 1, ";\n#endif\n");
1129 } else {
1130 InsertText(LocStart, "// ");
1131 }
1132}
1133
1134void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1135 SourceLocation Loc = prop->getAtLoc();
1136
1137 ReplaceText(Loc, 0, "// ");
1138 // FIXME: handle properties that are declared across multiple lines.
1139}
1140
1141void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1142 SourceLocation LocStart = CatDecl->getLocStart();
1143
1144 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001145 if (CatDecl->getIvarRBraceLoc().isValid()) {
1146 ReplaceText(LocStart, 1, "/** ");
1147 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1148 }
1149 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001150 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001151 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001152
Fariborz Jahanian11671902012-02-07 17:11:38 +00001153 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1154 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001155 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001156
1157 for (ObjCCategoryDecl::instmeth_iterator
1158 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1159 I != E; ++I)
1160 RewriteMethodDeclaration(*I);
1161 for (ObjCCategoryDecl::classmeth_iterator
1162 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1163 I != E; ++I)
1164 RewriteMethodDeclaration(*I);
1165
1166 // Lastly, comment out the @end.
1167 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001168 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001169}
1170
1171void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1172 SourceLocation LocStart = PDecl->getLocStart();
1173 assert(PDecl->isThisDeclarationADefinition());
1174
1175 // FIXME: handle protocol headers that are declared across multiple lines.
1176 ReplaceText(LocStart, 0, "// ");
1177
1178 for (ObjCProtocolDecl::instmeth_iterator
1179 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1180 I != E; ++I)
1181 RewriteMethodDeclaration(*I);
1182 for (ObjCProtocolDecl::classmeth_iterator
1183 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1184 I != E; ++I)
1185 RewriteMethodDeclaration(*I);
1186
1187 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1188 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001189 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001190
1191 // Lastly, comment out the @end.
1192 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001193 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001194
1195 // Must comment out @optional/@required
1196 const char *startBuf = SM->getCharacterData(LocStart);
1197 const char *endBuf = SM->getCharacterData(LocEnd);
1198 for (const char *p = startBuf; p < endBuf; p++) {
1199 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1200 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1201 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1202
1203 }
1204 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1205 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1206 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1207
1208 }
1209 }
1210}
1211
1212void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1213 SourceLocation LocStart = (*D.begin())->getLocStart();
1214 if (LocStart.isInvalid())
1215 llvm_unreachable("Invalid SourceLocation");
1216 // FIXME: handle forward protocol that are declared across multiple lines.
1217 ReplaceText(LocStart, 0, "// ");
1218}
1219
1220void
Craig Topper5603df42013-07-05 19:34:19 +00001221RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001222 SourceLocation LocStart = DG[0]->getLocStart();
1223 if (LocStart.isInvalid())
1224 llvm_unreachable("Invalid SourceLocation");
1225 // FIXME: handle forward protocol that are declared across multiple lines.
1226 ReplaceText(LocStart, 0, "// ");
1227}
1228
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001229void
1230RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1231 SourceLocation LocStart = LSD->getExternLoc();
1232 if (LocStart.isInvalid())
1233 llvm_unreachable("Invalid extern SourceLocation");
1234
1235 ReplaceText(LocStart, 0, "// ");
1236 if (!LSD->hasBraces())
1237 return;
1238 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1239 SourceLocation LocRBrace = LSD->getRBraceLoc();
1240 if (LocRBrace.isInvalid())
1241 llvm_unreachable("Invalid rbrace SourceLocation");
1242 ReplaceText(LocRBrace, 0, "// ");
1243}
1244
Fariborz Jahanian11671902012-02-07 17:11:38 +00001245void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1246 const FunctionType *&FPRetType) {
1247 if (T->isObjCQualifiedIdType())
1248 ResultStr += "id";
1249 else if (T->isFunctionPointerType() ||
1250 T->isBlockPointerType()) {
1251 // needs special handling, since pointer-to-functions have special
1252 // syntax (where a decaration models use).
1253 QualType retType = T;
1254 QualType PointeeTy;
1255 if (const PointerType* PT = retType->getAs<PointerType>())
1256 PointeeTy = PT->getPointeeType();
1257 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1258 PointeeTy = BPT->getPointeeType();
1259 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1260 ResultStr += FPRetType->getResultType().getAsString(
1261 Context->getPrintingPolicy());
1262 ResultStr += "(*";
1263 }
1264 } else
1265 ResultStr += T.getAsString(Context->getPrintingPolicy());
1266}
1267
1268void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1269 ObjCMethodDecl *OMD,
1270 std::string &ResultStr) {
1271 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1272 const FunctionType *FPRetType = 0;
1273 ResultStr += "\nstatic ";
1274 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1275 ResultStr += " ";
1276
1277 // Unique method name
1278 std::string NameStr;
1279
1280 if (OMD->isInstanceMethod())
1281 NameStr += "_I_";
1282 else
1283 NameStr += "_C_";
1284
1285 NameStr += IDecl->getNameAsString();
1286 NameStr += "_";
1287
1288 if (ObjCCategoryImplDecl *CID =
1289 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1290 NameStr += CID->getNameAsString();
1291 NameStr += "_";
1292 }
1293 // Append selector names, replacing ':' with '_'
1294 {
1295 std::string selString = OMD->getSelector().getAsString();
1296 int len = selString.size();
1297 for (int i = 0; i < len; i++)
1298 if (selString[i] == ':')
1299 selString[i] = '_';
1300 NameStr += selString;
1301 }
1302 // Remember this name for metadata emission
1303 MethodInternalNames[OMD] = NameStr;
1304 ResultStr += NameStr;
1305
1306 // Rewrite arguments
1307 ResultStr += "(";
1308
1309 // invisible arguments
1310 if (OMD->isInstanceMethod()) {
1311 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1312 selfTy = Context->getPointerType(selfTy);
1313 if (!LangOpts.MicrosoftExt) {
1314 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1315 ResultStr += "struct ";
1316 }
1317 // When rewriting for Microsoft, explicitly omit the structure name.
1318 ResultStr += IDecl->getNameAsString();
1319 ResultStr += " *";
1320 }
1321 else
1322 ResultStr += Context->getObjCClassType().getAsString(
1323 Context->getPrintingPolicy());
1324
1325 ResultStr += " self, ";
1326 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1327 ResultStr += " _cmd";
1328
1329 // Method arguments.
1330 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1331 E = OMD->param_end(); PI != E; ++PI) {
1332 ParmVarDecl *PDecl = *PI;
1333 ResultStr += ", ";
1334 if (PDecl->getType()->isObjCQualifiedIdType()) {
1335 ResultStr += "id ";
1336 ResultStr += PDecl->getNameAsString();
1337 } else {
1338 std::string Name = PDecl->getNameAsString();
1339 QualType QT = PDecl->getType();
1340 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001341 (void)convertBlockPointerToFunctionPointer(QT);
1342 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001343 ResultStr += Name;
1344 }
1345 }
1346 if (OMD->isVariadic())
1347 ResultStr += ", ...";
1348 ResultStr += ") ";
1349
1350 if (FPRetType) {
1351 ResultStr += ")"; // close the precedence "scope" for "*".
1352
1353 // Now, emit the argument types (if any).
1354 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1355 ResultStr += "(";
1356 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1357 if (i) ResultStr += ", ";
1358 std::string ParamStr = FT->getArgType(i).getAsString(
1359 Context->getPrintingPolicy());
1360 ResultStr += ParamStr;
1361 }
1362 if (FT->isVariadic()) {
1363 if (FT->getNumArgs()) ResultStr += ", ";
1364 ResultStr += "...";
1365 }
1366 ResultStr += ")";
1367 } else {
1368 ResultStr += "()";
1369 }
1370 }
1371}
1372void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1373 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1374 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1375
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001376 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001377 if (IMD->getIvarRBraceLoc().isValid()) {
1378 ReplaceText(IMD->getLocStart(), 1, "/** ");
1379 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001380 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001381 else {
1382 InsertText(IMD->getLocStart(), "// ");
1383 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001384 }
1385 else
1386 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001387
1388 for (ObjCCategoryImplDecl::instmeth_iterator
1389 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1390 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1391 I != E; ++I) {
1392 std::string ResultStr;
1393 ObjCMethodDecl *OMD = *I;
1394 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1395 SourceLocation LocStart = OMD->getLocStart();
1396 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1397
1398 const char *startBuf = SM->getCharacterData(LocStart);
1399 const char *endBuf = SM->getCharacterData(LocEnd);
1400 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1401 }
1402
1403 for (ObjCCategoryImplDecl::classmeth_iterator
1404 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1405 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1406 I != E; ++I) {
1407 std::string ResultStr;
1408 ObjCMethodDecl *OMD = *I;
1409 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1410 SourceLocation LocStart = OMD->getLocStart();
1411 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1412
1413 const char *startBuf = SM->getCharacterData(LocStart);
1414 const char *endBuf = SM->getCharacterData(LocEnd);
1415 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1416 }
1417 for (ObjCCategoryImplDecl::propimpl_iterator
1418 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1419 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1420 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001421 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001422 }
1423
1424 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1425}
1426
1427void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001428 // Do not synthesize more than once.
1429 if (ObjCSynthesizedStructs.count(ClassDecl))
1430 return;
1431 // Make sure super class's are written before current class is written.
1432 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1433 while (SuperClass) {
1434 RewriteInterfaceDecl(SuperClass);
1435 SuperClass = SuperClass->getSuperClass();
1436 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001437 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001438 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001439 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001440 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001441 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1442
Fariborz Jahanianff513382012-02-15 22:01:47 +00001443 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001444 // Mark this typedef as having been written into its c++ equivalent.
1445 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001446
1447 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001448 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001449 RewriteProperty(*I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001450 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001451 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001452 I != E; ++I)
1453 RewriteMethodDeclaration(*I);
1454 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001455 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001456 I != E; ++I)
1457 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001458
Fariborz Jahanianff513382012-02-15 22:01:47 +00001459 // Lastly, comment out the @end.
1460 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001461 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001462 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001463}
1464
1465Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1466 SourceRange OldRange = PseudoOp->getSourceRange();
1467
1468 // We just magically know some things about the structure of this
1469 // expression.
1470 ObjCMessageExpr *OldMsg =
1471 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1472 PseudoOp->getNumSemanticExprs() - 1));
1473
1474 // Because the rewriter doesn't allow us to rewrite rewritten code,
1475 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001476 Expr *Base;
1477 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001478 {
1479 DisableReplaceStmtScope S(*this);
1480
1481 // Rebuild the base expression if we have one.
1482 Base = 0;
1483 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1484 Base = OldMsg->getInstanceReceiver();
1485 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1486 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1487 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001488
1489 unsigned numArgs = OldMsg->getNumArgs();
1490 for (unsigned i = 0; i < numArgs; i++) {
1491 Expr *Arg = OldMsg->getArg(i);
1492 if (isa<OpaqueValueExpr>(Arg))
1493 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1494 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1495 Args.push_back(Arg);
1496 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001497 }
1498
1499 // TODO: avoid this copy.
1500 SmallVector<SourceLocation, 1> SelLocs;
1501 OldMsg->getSelectorLocs(SelLocs);
1502
1503 ObjCMessageExpr *NewMsg = 0;
1504 switch (OldMsg->getReceiverKind()) {
1505 case ObjCMessageExpr::Class:
1506 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1507 OldMsg->getValueKind(),
1508 OldMsg->getLeftLoc(),
1509 OldMsg->getClassReceiverTypeInfo(),
1510 OldMsg->getSelector(),
1511 SelLocs,
1512 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001513 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001514 OldMsg->getRightLoc(),
1515 OldMsg->isImplicit());
1516 break;
1517
1518 case ObjCMessageExpr::Instance:
1519 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1520 OldMsg->getValueKind(),
1521 OldMsg->getLeftLoc(),
1522 Base,
1523 OldMsg->getSelector(),
1524 SelLocs,
1525 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001526 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001527 OldMsg->getRightLoc(),
1528 OldMsg->isImplicit());
1529 break;
1530
1531 case ObjCMessageExpr::SuperClass:
1532 case ObjCMessageExpr::SuperInstance:
1533 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1534 OldMsg->getValueKind(),
1535 OldMsg->getLeftLoc(),
1536 OldMsg->getSuperLoc(),
1537 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1538 OldMsg->getSuperType(),
1539 OldMsg->getSelector(),
1540 SelLocs,
1541 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001542 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001543 OldMsg->getRightLoc(),
1544 OldMsg->isImplicit());
1545 break;
1546 }
1547
1548 Stmt *Replacement = SynthMessageExpr(NewMsg);
1549 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1550 return Replacement;
1551}
1552
1553Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1554 SourceRange OldRange = PseudoOp->getSourceRange();
1555
1556 // We just magically know some things about the structure of this
1557 // expression.
1558 ObjCMessageExpr *OldMsg =
1559 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1560
1561 // Because the rewriter doesn't allow us to rewrite rewritten code,
1562 // we need to suppress rewriting the sub-statements.
1563 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001564 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001565 {
1566 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001567 // Rebuild the base expression if we have one.
1568 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1569 Base = OldMsg->getInstanceReceiver();
1570 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1571 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1572 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001573 unsigned numArgs = OldMsg->getNumArgs();
1574 for (unsigned i = 0; i < numArgs; i++) {
1575 Expr *Arg = OldMsg->getArg(i);
1576 if (isa<OpaqueValueExpr>(Arg))
1577 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1578 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1579 Args.push_back(Arg);
1580 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001581 }
1582
1583 // Intentionally empty.
1584 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001585
1586 ObjCMessageExpr *NewMsg = 0;
1587 switch (OldMsg->getReceiverKind()) {
1588 case ObjCMessageExpr::Class:
1589 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1590 OldMsg->getValueKind(),
1591 OldMsg->getLeftLoc(),
1592 OldMsg->getClassReceiverTypeInfo(),
1593 OldMsg->getSelector(),
1594 SelLocs,
1595 OldMsg->getMethodDecl(),
1596 Args,
1597 OldMsg->getRightLoc(),
1598 OldMsg->isImplicit());
1599 break;
1600
1601 case ObjCMessageExpr::Instance:
1602 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1603 OldMsg->getValueKind(),
1604 OldMsg->getLeftLoc(),
1605 Base,
1606 OldMsg->getSelector(),
1607 SelLocs,
1608 OldMsg->getMethodDecl(),
1609 Args,
1610 OldMsg->getRightLoc(),
1611 OldMsg->isImplicit());
1612 break;
1613
1614 case ObjCMessageExpr::SuperClass:
1615 case ObjCMessageExpr::SuperInstance:
1616 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1617 OldMsg->getValueKind(),
1618 OldMsg->getLeftLoc(),
1619 OldMsg->getSuperLoc(),
1620 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1621 OldMsg->getSuperType(),
1622 OldMsg->getSelector(),
1623 SelLocs,
1624 OldMsg->getMethodDecl(),
1625 Args,
1626 OldMsg->getRightLoc(),
1627 OldMsg->isImplicit());
1628 break;
1629 }
1630
1631 Stmt *Replacement = SynthMessageExpr(NewMsg);
1632 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1633 return Replacement;
1634}
1635
1636/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001637/// ((NSUInteger (*)
1638/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001639/// (void *)objc_msgSend)((id)l_collection,
1640/// sel_registerName(
1641/// "countByEnumeratingWithState:objects:count:"),
1642/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001643/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001644///
1645void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001646 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1647 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001648 buf += "\n\t\t";
1649 buf += "((id)l_collection,\n\t\t";
1650 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1651 buf += "\n\t\t";
1652 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001653 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001654}
1655
1656/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1657/// statement to exit to its outer synthesized loop.
1658///
1659Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1660 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1661 return S;
1662 // replace break with goto __break_label
1663 std::string buf;
1664
1665 SourceLocation startLoc = S->getLocStart();
1666 buf = "goto __break_label_";
1667 buf += utostr(ObjCBcLabelNo.back());
1668 ReplaceText(startLoc, strlen("break"), buf);
1669
1670 return 0;
1671}
1672
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001673void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1674 SourceLocation Loc,
1675 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001676 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001677 LineString += "\n#line ";
1678 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1679 LineString += utostr(PLoc.getLine());
1680 LineString += " \"";
1681 LineString += Lexer::Stringify(PLoc.getFilename());
1682 LineString += "\"\n";
1683 }
1684}
1685
Fariborz Jahanian11671902012-02-07 17:11:38 +00001686/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1687/// statement to continue with its inner synthesized loop.
1688///
1689Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1690 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1691 return S;
1692 // replace continue with goto __continue_label
1693 std::string buf;
1694
1695 SourceLocation startLoc = S->getLocStart();
1696 buf = "goto __continue_label_";
1697 buf += utostr(ObjCBcLabelNo.back());
1698 ReplaceText(startLoc, strlen("continue"), buf);
1699
1700 return 0;
1701}
1702
1703/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1704/// It rewrites:
1705/// for ( type elem in collection) { stmts; }
1706
1707/// Into:
1708/// {
1709/// type elem;
1710/// struct __objcFastEnumerationState enumState = { 0 };
1711/// id __rw_items[16];
1712/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001713/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001714/// objects:__rw_items count:16];
1715/// if (limit) {
1716/// unsigned long startMutations = *enumState.mutationsPtr;
1717/// do {
1718/// unsigned long counter = 0;
1719/// do {
1720/// if (startMutations != *enumState.mutationsPtr)
1721/// objc_enumerationMutation(l_collection);
1722/// elem = (type)enumState.itemsPtr[counter++];
1723/// stmts;
1724/// __continue_label: ;
1725/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001726/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1727/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001728/// elem = nil;
1729/// __break_label: ;
1730/// }
1731/// else
1732/// elem = nil;
1733/// }
1734///
1735Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1736 SourceLocation OrigEnd) {
1737 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1738 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1739 "ObjCForCollectionStmt Statement stack mismatch");
1740 assert(!ObjCBcLabelNo.empty() &&
1741 "ObjCForCollectionStmt - Label No stack empty");
1742
1743 SourceLocation startLoc = S->getLocStart();
1744 const char *startBuf = SM->getCharacterData(startLoc);
1745 StringRef elementName;
1746 std::string elementTypeAsString;
1747 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001748 // line directive first.
1749 SourceLocation ForEachLoc = S->getForLoc();
1750 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1751 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001752 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1753 // type elem;
1754 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1755 QualType ElementType = cast<ValueDecl>(D)->getType();
1756 if (ElementType->isObjCQualifiedIdType() ||
1757 ElementType->isObjCQualifiedInterfaceType())
1758 // Simply use 'id' for all qualified types.
1759 elementTypeAsString = "id";
1760 else
1761 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1762 buf += elementTypeAsString;
1763 buf += " ";
1764 elementName = D->getName();
1765 buf += elementName;
1766 buf += ";\n\t";
1767 }
1768 else {
1769 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1770 elementName = DR->getDecl()->getName();
1771 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1772 if (VD->getType()->isObjCQualifiedIdType() ||
1773 VD->getType()->isObjCQualifiedInterfaceType())
1774 // Simply use 'id' for all qualified types.
1775 elementTypeAsString = "id";
1776 else
1777 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1778 }
1779
1780 // struct __objcFastEnumerationState enumState = { 0 };
1781 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1782 // id __rw_items[16];
1783 buf += "id __rw_items[16];\n\t";
1784 // id l_collection = (id)
1785 buf += "id l_collection = (id)";
1786 // Find start location of 'collection' the hard way!
1787 const char *startCollectionBuf = startBuf;
1788 startCollectionBuf += 3; // skip 'for'
1789 startCollectionBuf = strchr(startCollectionBuf, '(');
1790 startCollectionBuf++; // skip '('
1791 // find 'in' and skip it.
1792 while (*startCollectionBuf != ' ' ||
1793 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1794 (*(startCollectionBuf+3) != ' ' &&
1795 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1796 startCollectionBuf++;
1797 startCollectionBuf += 3;
1798
1799 // Replace: "for (type element in" with string constructed thus far.
1800 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1801 // Replace ')' in for '(' type elem in collection ')' with ';'
1802 SourceLocation rightParenLoc = S->getRParenLoc();
1803 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1804 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1805 buf = ";\n\t";
1806
1807 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1808 // objects:__rw_items count:16];
1809 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001810 // NSUInteger limit =
1811 // ((NSUInteger (*)
1812 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001813 // (void *)objc_msgSend)((id)l_collection,
1814 // sel_registerName(
1815 // "countByEnumeratingWithState:objects:count:"),
1816 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001817 // (id *)__rw_items, (NSUInteger)16);
1818 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001819 SynthCountByEnumWithState(buf);
1820 buf += ";\n\t";
1821 /// if (limit) {
1822 /// unsigned long startMutations = *enumState.mutationsPtr;
1823 /// do {
1824 /// unsigned long counter = 0;
1825 /// do {
1826 /// if (startMutations != *enumState.mutationsPtr)
1827 /// objc_enumerationMutation(l_collection);
1828 /// elem = (type)enumState.itemsPtr[counter++];
1829 buf += "if (limit) {\n\t";
1830 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1831 buf += "do {\n\t\t";
1832 buf += "unsigned long counter = 0;\n\t\t";
1833 buf += "do {\n\t\t\t";
1834 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1835 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1836 buf += elementName;
1837 buf += " = (";
1838 buf += elementTypeAsString;
1839 buf += ")enumState.itemsPtr[counter++];";
1840 // Replace ')' in for '(' type elem in collection ')' with all of these.
1841 ReplaceText(lparenLoc, 1, buf);
1842
1843 /// __continue_label: ;
1844 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001845 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1846 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001847 /// elem = nil;
1848 /// __break_label: ;
1849 /// }
1850 /// else
1851 /// elem = nil;
1852 /// }
1853 ///
1854 buf = ";\n\t";
1855 buf += "__continue_label_";
1856 buf += utostr(ObjCBcLabelNo.back());
1857 buf += ": ;";
1858 buf += "\n\t\t";
1859 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001860 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001861 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001862 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001863 buf += elementName;
1864 buf += " = ((";
1865 buf += elementTypeAsString;
1866 buf += ")0);\n\t";
1867 buf += "__break_label_";
1868 buf += utostr(ObjCBcLabelNo.back());
1869 buf += ": ;\n\t";
1870 buf += "}\n\t";
1871 buf += "else\n\t\t";
1872 buf += elementName;
1873 buf += " = ((";
1874 buf += elementTypeAsString;
1875 buf += ")0);\n\t";
1876 buf += "}\n";
1877
1878 // Insert all these *after* the statement body.
1879 // FIXME: If this should support Obj-C++, support CXXTryStmt
1880 if (isa<CompoundStmt>(S->getBody())) {
1881 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1882 InsertText(endBodyLoc, buf);
1883 } else {
1884 /* Need to treat single statements specially. For example:
1885 *
1886 * for (A *a in b) if (stuff()) break;
1887 * for (A *a in b) xxxyy;
1888 *
1889 * The following code simply scans ahead to the semi to find the actual end.
1890 */
1891 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1892 const char *semiBuf = strchr(stmtBuf, ';');
1893 assert(semiBuf && "Can't find ';'");
1894 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1895 InsertText(endBodyLoc, buf);
1896 }
1897 Stmts.pop_back();
1898 ObjCBcLabelNo.pop_back();
1899 return 0;
1900}
1901
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001902static void Write_RethrowObject(std::string &buf) {
1903 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1904 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1905 buf += "\tid rethrow;\n";
1906 buf += "\t} _fin_force_rethow(_rethrow);";
1907}
1908
Fariborz Jahanian11671902012-02-07 17:11:38 +00001909/// RewriteObjCSynchronizedStmt -
1910/// This routine rewrites @synchronized(expr) stmt;
1911/// into:
1912/// objc_sync_enter(expr);
1913/// @try stmt @finally { objc_sync_exit(expr); }
1914///
1915Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1916 // Get the start location and compute the semi location.
1917 SourceLocation startLoc = S->getLocStart();
1918 const char *startBuf = SM->getCharacterData(startLoc);
1919
1920 assert((*startBuf == '@') && "bogus @synchronized location");
1921
1922 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001923 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1924 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001925 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001926
Fariborz Jahanian11671902012-02-07 17:11:38 +00001927 const char *lparenBuf = startBuf;
1928 while (*lparenBuf != '(') lparenBuf++;
1929 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001930
1931 buf = "; objc_sync_enter(_sync_obj);\n";
1932 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1933 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1934 buf += "\n\tid sync_exit;";
1935 buf += "\n\t} _sync_exit(_sync_obj);\n";
1936
1937 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1938 // the sync expression is typically a message expression that's already
1939 // been rewritten! (which implies the SourceLocation's are invalid).
1940 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1941 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1942 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1943 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1944
1945 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1946 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1947 assert (*LBraceLocBuf == '{');
1948 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001949
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001950 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001951 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1952 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001953
1954 buf = "} catch (id e) {_rethrow = e;}\n";
1955 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001956 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001957 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001958
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001959 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001960
Fariborz Jahanian11671902012-02-07 17:11:38 +00001961 return 0;
1962}
1963
1964void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1965{
1966 // Perform a bottom up traversal of all children.
1967 for (Stmt::child_range CI = S->children(); CI; ++CI)
1968 if (*CI)
1969 WarnAboutReturnGotoStmts(*CI);
1970
1971 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1972 Diags.Report(Context->getFullLoc(S->getLocStart()),
1973 TryFinallyContainsReturnDiag);
1974 }
1975 return;
1976}
1977
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001978Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1979 SourceLocation startLoc = S->getAtLoc();
1980 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001981 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1982 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001983
1984 return 0;
1985}
1986
Fariborz Jahanian11671902012-02-07 17:11:38 +00001987Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001988 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001989 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001990 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001991 SourceLocation TryLocation = S->getAtTryLoc();
1992 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001993
1994 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001995 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001996 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001997 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001998 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001999 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002000 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002001 // Get the start location and compute the semi location.
2002 SourceLocation startLoc = S->getLocStart();
2003 const char *startBuf = SM->getCharacterData(startLoc);
2004
2005 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002006 if (finalStmt)
2007 ReplaceText(startLoc, 1, buf);
2008 else
2009 // @try -> try
2010 ReplaceText(startLoc, 1, "");
2011
Fariborz Jahanian11671902012-02-07 17:11:38 +00002012 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2013 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002014 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002015
Fariborz Jahanian11671902012-02-07 17:11:38 +00002016 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002017 bool AtRemoved = false;
2018 if (catchDecl) {
2019 QualType t = catchDecl->getType();
2020 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2021 // Should be a pointer to a class.
2022 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2023 if (IDecl) {
2024 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002025 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2026
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002027 startBuf = SM->getCharacterData(startLoc);
2028 assert((*startBuf == '@') && "bogus @catch location");
2029 SourceLocation rParenLoc = Catch->getRParenLoc();
2030 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2031
2032 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002033 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002034 Result += " *_"; Result += catchDecl->getNameAsString();
2035 Result += ")";
2036 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2037 // Foo *e = (Foo *)_e;
2038 Result.clear();
2039 Result = "{ ";
2040 Result += IDecl->getNameAsString();
2041 Result += " *"; Result += catchDecl->getNameAsString();
2042 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2043 Result += "_"; Result += catchDecl->getNameAsString();
2044
2045 Result += "; ";
2046 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2047 ReplaceText(lBraceLoc, 1, Result);
2048 AtRemoved = true;
2049 }
2050 }
2051 }
2052 if (!AtRemoved)
2053 // @catch -> catch
2054 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002055
Fariborz Jahanian11671902012-02-07 17:11:38 +00002056 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002057 if (finalStmt) {
2058 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002059 SourceLocation FinallyLoc = finalStmt->getLocStart();
2060
2061 if (noCatch) {
2062 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2063 buf += "catch (id e) {_rethrow = e;}\n";
2064 }
2065 else {
2066 buf += "}\n";
2067 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2068 buf += "catch (id e) {_rethrow = e;}\n";
2069 }
2070
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002071 SourceLocation startFinalLoc = finalStmt->getLocStart();
2072 ReplaceText(startFinalLoc, 8, buf);
2073 Stmt *body = finalStmt->getFinallyBody();
2074 SourceLocation startFinalBodyLoc = body->getLocStart();
2075 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002076 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002077 ReplaceText(startFinalBodyLoc, 1, buf);
2078
2079 SourceLocation endFinalBodyLoc = body->getLocEnd();
2080 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002081 // Now check for any return/continue/go statements within the @try.
2082 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002083 }
2084
Fariborz Jahanian11671902012-02-07 17:11:38 +00002085 return 0;
2086}
2087
2088// This can't be done with ReplaceStmt(S, ThrowExpr), since
2089// the throw expression is typically a message expression that's already
2090// been rewritten! (which implies the SourceLocation's are invalid).
2091Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2092 // Get the start location and compute the semi location.
2093 SourceLocation startLoc = S->getLocStart();
2094 const char *startBuf = SM->getCharacterData(startLoc);
2095
2096 assert((*startBuf == '@') && "bogus @throw location");
2097
2098 std::string buf;
2099 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2100 if (S->getThrowExpr())
2101 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002102 else
2103 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002104
2105 // handle "@ throw" correctly.
2106 const char *wBuf = strchr(startBuf, 'w');
2107 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2108 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2109
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002110 SourceLocation endLoc = S->getLocEnd();
2111 const char *endBuf = SM->getCharacterData(endLoc);
2112 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002113 assert((*semiBuf == ';') && "@throw: can't find ';'");
2114 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002115 if (S->getThrowExpr())
2116 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002117 return 0;
2118}
2119
2120Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2121 // Create a new string expression.
2122 QualType StrType = Context->getPointerType(Context->CharTy);
2123 std::string StrEncoding;
2124 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2125 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2126 StringLiteral::Ascii, false,
2127 StrType, SourceLocation());
2128 ReplaceStmt(Exp, Replacement);
2129
2130 // Replace this subexpr in the parent.
2131 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2132 return Replacement;
2133}
2134
2135Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2136 if (!SelGetUidFunctionDecl)
2137 SynthSelGetUidFunctionDecl();
2138 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2139 // Create a call to sel_registerName("selName").
2140 SmallVector<Expr*, 8> SelExprs;
2141 QualType argType = Context->getPointerType(Context->CharTy);
2142 SelExprs.push_back(StringLiteral::Create(*Context,
2143 Exp->getSelector().getAsString(),
2144 StringLiteral::Ascii, false,
2145 argType, SourceLocation()));
2146 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2147 &SelExprs[0], SelExprs.size());
2148 ReplaceStmt(Exp, SelExp);
2149 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2150 return SelExp;
2151}
2152
2153CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2154 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2155 SourceLocation EndLoc) {
2156 // Get the type, we will need to reference it in a couple spots.
2157 QualType msgSendType = FD->getType();
2158
2159 // Create a reference to the objc_msgSend() declaration.
2160 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002161 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002162
2163 // Now, we cast the reference to a pointer to the objc_msgSend type.
2164 QualType pToFunc = Context->getPointerType(msgSendType);
2165 ImplicitCastExpr *ICE =
2166 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2167 DRE, 0, VK_RValue);
2168
2169 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2170
2171 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002172 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002173 FT->getCallResultType(*Context),
2174 VK_RValue, EndLoc);
2175 return Exp;
2176}
2177
2178static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2179 const char *&startRef, const char *&endRef) {
2180 while (startBuf < endBuf) {
2181 if (*startBuf == '<')
2182 startRef = startBuf; // mark the start.
2183 if (*startBuf == '>') {
2184 if (startRef && *startRef == '<') {
2185 endRef = startBuf; // mark the end.
2186 return true;
2187 }
2188 return false;
2189 }
2190 startBuf++;
2191 }
2192 return false;
2193}
2194
2195static void scanToNextArgument(const char *&argRef) {
2196 int angle = 0;
2197 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2198 if (*argRef == '<')
2199 angle++;
2200 else if (*argRef == '>')
2201 angle--;
2202 argRef++;
2203 }
2204 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2205}
2206
2207bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2208 if (T->isObjCQualifiedIdType())
2209 return true;
2210 if (const PointerType *PT = T->getAs<PointerType>()) {
2211 if (PT->getPointeeType()->isObjCQualifiedIdType())
2212 return true;
2213 }
2214 if (T->isObjCObjectPointerType()) {
2215 T = T->getPointeeType();
2216 return T->isObjCQualifiedInterfaceType();
2217 }
2218 if (T->isArrayType()) {
2219 QualType ElemTy = Context->getBaseElementType(T);
2220 return needToScanForQualifiers(ElemTy);
2221 }
2222 return false;
2223}
2224
2225void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2226 QualType Type = E->getType();
2227 if (needToScanForQualifiers(Type)) {
2228 SourceLocation Loc, EndLoc;
2229
2230 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2231 Loc = ECE->getLParenLoc();
2232 EndLoc = ECE->getRParenLoc();
2233 } else {
2234 Loc = E->getLocStart();
2235 EndLoc = E->getLocEnd();
2236 }
2237 // This will defend against trying to rewrite synthesized expressions.
2238 if (Loc.isInvalid() || EndLoc.isInvalid())
2239 return;
2240
2241 const char *startBuf = SM->getCharacterData(Loc);
2242 const char *endBuf = SM->getCharacterData(EndLoc);
2243 const char *startRef = 0, *endRef = 0;
2244 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2245 // Get the locations of the startRef, endRef.
2246 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2247 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2248 // Comment out the protocol references.
2249 InsertText(LessLoc, "/*");
2250 InsertText(GreaterLoc, "*/");
2251 }
2252 }
2253}
2254
2255void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2256 SourceLocation Loc;
2257 QualType Type;
2258 const FunctionProtoType *proto = 0;
2259 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2260 Loc = VD->getLocation();
2261 Type = VD->getType();
2262 }
2263 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2264 Loc = FD->getLocation();
2265 // Check for ObjC 'id' and class types that have been adorned with protocol
2266 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2267 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2268 assert(funcType && "missing function type");
2269 proto = dyn_cast<FunctionProtoType>(funcType);
2270 if (!proto)
2271 return;
2272 Type = proto->getResultType();
2273 }
2274 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2275 Loc = FD->getLocation();
2276 Type = FD->getType();
2277 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002278 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2279 Loc = TD->getLocation();
2280 Type = TD->getUnderlyingType();
2281 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002282 else
2283 return;
2284
2285 if (needToScanForQualifiers(Type)) {
2286 // Since types are unique, we need to scan the buffer.
2287
2288 const char *endBuf = SM->getCharacterData(Loc);
2289 const char *startBuf = endBuf;
2290 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2291 startBuf--; // scan backward (from the decl location) for return type.
2292 const char *startRef = 0, *endRef = 0;
2293 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2294 // Get the locations of the startRef, endRef.
2295 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2296 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2297 // Comment out the protocol references.
2298 InsertText(LessLoc, "/*");
2299 InsertText(GreaterLoc, "*/");
2300 }
2301 }
2302 if (!proto)
2303 return; // most likely, was a variable
2304 // Now check arguments.
2305 const char *startBuf = SM->getCharacterData(Loc);
2306 const char *startFuncBuf = startBuf;
2307 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2308 if (needToScanForQualifiers(proto->getArgType(i))) {
2309 // Since types are unique, we need to scan the buffer.
2310
2311 const char *endBuf = startBuf;
2312 // scan forward (from the decl location) for argument types.
2313 scanToNextArgument(endBuf);
2314 const char *startRef = 0, *endRef = 0;
2315 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2316 // Get the locations of the startRef, endRef.
2317 SourceLocation LessLoc =
2318 Loc.getLocWithOffset(startRef-startFuncBuf);
2319 SourceLocation GreaterLoc =
2320 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2321 // Comment out the protocol references.
2322 InsertText(LessLoc, "/*");
2323 InsertText(GreaterLoc, "*/");
2324 }
2325 startBuf = ++endBuf;
2326 }
2327 else {
2328 // If the function name is derived from a macro expansion, then the
2329 // argument buffer will not follow the name. Need to speak with Chris.
2330 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2331 startBuf++; // scan forward (from the decl location) for argument types.
2332 startBuf++;
2333 }
2334 }
2335}
2336
2337void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2338 QualType QT = ND->getType();
2339 const Type* TypePtr = QT->getAs<Type>();
2340 if (!isa<TypeOfExprType>(TypePtr))
2341 return;
2342 while (isa<TypeOfExprType>(TypePtr)) {
2343 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2344 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2345 TypePtr = QT->getAs<Type>();
2346 }
2347 // FIXME. This will not work for multiple declarators; as in:
2348 // __typeof__(a) b,c,d;
2349 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2350 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2351 const char *startBuf = SM->getCharacterData(DeclLoc);
2352 if (ND->getInit()) {
2353 std::string Name(ND->getNameAsString());
2354 TypeAsString += " " + Name + " = ";
2355 Expr *E = ND->getInit();
2356 SourceLocation startLoc;
2357 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2358 startLoc = ECE->getLParenLoc();
2359 else
2360 startLoc = E->getLocStart();
2361 startLoc = SM->getExpansionLoc(startLoc);
2362 const char *endBuf = SM->getCharacterData(startLoc);
2363 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2364 }
2365 else {
2366 SourceLocation X = ND->getLocEnd();
2367 X = SM->getExpansionLoc(X);
2368 const char *endBuf = SM->getCharacterData(X);
2369 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2370 }
2371}
2372
2373// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2374void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2375 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2376 SmallVector<QualType, 16> ArgTys;
2377 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2378 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002379 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002380 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002381 SourceLocation(),
2382 SourceLocation(),
2383 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002384 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002385}
2386
2387void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2388 // declared in <objc/objc.h>
2389 if (FD->getIdentifier() &&
2390 FD->getName() == "sel_registerName") {
2391 SelGetUidFunctionDecl = FD;
2392 return;
2393 }
2394 RewriteObjCQualifiedInterfaceTypes(FD);
2395}
2396
2397void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2398 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2399 const char *argPtr = TypeString.c_str();
2400 if (!strchr(argPtr, '^')) {
2401 Str += TypeString;
2402 return;
2403 }
2404 while (*argPtr) {
2405 Str += (*argPtr == '^' ? '*' : *argPtr);
2406 argPtr++;
2407 }
2408}
2409
2410// FIXME. Consolidate this routine with RewriteBlockPointerType.
2411void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2412 ValueDecl *VD) {
2413 QualType Type = VD->getType();
2414 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2415 const char *argPtr = TypeString.c_str();
2416 int paren = 0;
2417 while (*argPtr) {
2418 switch (*argPtr) {
2419 case '(':
2420 Str += *argPtr;
2421 paren++;
2422 break;
2423 case ')':
2424 Str += *argPtr;
2425 paren--;
2426 break;
2427 case '^':
2428 Str += '*';
2429 if (paren == 1)
2430 Str += VD->getNameAsString();
2431 break;
2432 default:
2433 Str += *argPtr;
2434 break;
2435 }
2436 argPtr++;
2437 }
2438}
2439
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002440void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2441 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2442 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2443 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2444 if (!proto)
2445 return;
2446 QualType Type = proto->getResultType();
2447 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2448 FdStr += " ";
2449 FdStr += FD->getName();
2450 FdStr += "(";
2451 unsigned numArgs = proto->getNumArgs();
2452 for (unsigned i = 0; i < numArgs; i++) {
2453 QualType ArgType = proto->getArgType(i);
2454 RewriteBlockPointerType(FdStr, ArgType);
2455 if (i+1 < numArgs)
2456 FdStr += ", ";
2457 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002458 if (FD->isVariadic()) {
2459 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2460 }
2461 else
2462 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002463 InsertText(FunLocStart, FdStr);
2464}
2465
Benjamin Kramer60509af2013-09-09 14:48:42 +00002466// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2467void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2468 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002469 return;
2470 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2471 SmallVector<QualType, 16> ArgTys;
2472 QualType argT = Context->getObjCIdType();
2473 assert(!argT.isNull() && "Can't find 'id' type");
2474 ArgTys.push_back(argT);
2475 ArgTys.push_back(argT);
2476 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002477 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002478 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002479 SourceLocation(),
2480 SourceLocation(),
2481 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002482 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002483}
2484
2485// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2486void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2487 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2488 SmallVector<QualType, 16> ArgTys;
2489 QualType argT = Context->getObjCIdType();
2490 assert(!argT.isNull() && "Can't find 'id' type");
2491 ArgTys.push_back(argT);
2492 argT = Context->getObjCSelType();
2493 assert(!argT.isNull() && "Can't find 'SEL' type");
2494 ArgTys.push_back(argT);
2495 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002496 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002497 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002498 SourceLocation(),
2499 SourceLocation(),
2500 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002501 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002502}
2503
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002504// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2506 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002507 SmallVector<QualType, 2> ArgTys;
2508 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002509 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002510 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002511 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002512 SourceLocation(),
2513 SourceLocation(),
2514 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002515 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002516}
2517
2518// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2519void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2520 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2521 SmallVector<QualType, 16> ArgTys;
2522 QualType argT = Context->getObjCIdType();
2523 assert(!argT.isNull() && "Can't find 'id' type");
2524 ArgTys.push_back(argT);
2525 argT = Context->getObjCSelType();
2526 assert(!argT.isNull() && "Can't find 'SEL' type");
2527 ArgTys.push_back(argT);
2528 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002529 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002530 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002531 SourceLocation(),
2532 SourceLocation(),
2533 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002534 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002535}
2536
2537// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002538// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002539void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2540 IdentifierInfo *msgSendIdent =
2541 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002542 SmallVector<QualType, 2> ArgTys;
2543 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002544 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002545 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002546 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2547 SourceLocation(),
2548 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002549 msgSendIdent,
2550 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002551 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002552}
2553
2554// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2555void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2556 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2557 SmallVector<QualType, 16> ArgTys;
2558 QualType argT = Context->getObjCIdType();
2559 assert(!argT.isNull() && "Can't find 'id' type");
2560 ArgTys.push_back(argT);
2561 argT = Context->getObjCSelType();
2562 assert(!argT.isNull() && "Can't find 'SEL' type");
2563 ArgTys.push_back(argT);
2564 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002565 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002566 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002567 SourceLocation(),
2568 SourceLocation(),
2569 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002570 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002571}
2572
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002573// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002574void RewriteModernObjC::SynthGetClassFunctionDecl() {
2575 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2576 SmallVector<QualType, 16> ArgTys;
2577 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002578 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002579 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002580 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002581 SourceLocation(),
2582 SourceLocation(),
2583 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002584 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002585}
2586
2587// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2588void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2589 IdentifierInfo *getSuperClassIdent =
2590 &Context->Idents.get("class_getSuperclass");
2591 SmallVector<QualType, 16> ArgTys;
2592 ArgTys.push_back(Context->getObjCClassType());
2593 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002594 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002595 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2596 SourceLocation(),
2597 SourceLocation(),
2598 getSuperClassIdent,
2599 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002600 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002601}
2602
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002603// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002604void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2605 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2606 SmallVector<QualType, 16> ArgTys;
2607 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002608 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002609 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002610 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002611 SourceLocation(),
2612 SourceLocation(),
2613 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002614 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002615}
2616
2617Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2618 QualType strType = getConstantStringStructType();
2619
2620 std::string S = "__NSConstantStringImpl_";
2621
2622 std::string tmpName = InFileName;
2623 unsigned i;
2624 for (i=0; i < tmpName.length(); i++) {
2625 char c = tmpName.at(i);
2626 // replace any non alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002627 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002628 tmpName[i] = '_';
2629 }
2630 S += tmpName;
2631 S += "_";
2632 S += utostr(NumObjCStringLiterals++);
2633
2634 Preamble += "static __NSConstantStringImpl " + S;
2635 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2636 Preamble += "0x000007c8,"; // utf8_str
2637 // The pretty printer for StringLiteral handles escape characters properly.
2638 std::string prettyBufS;
2639 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002640 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002641 Preamble += prettyBuf.str();
2642 Preamble += ",";
2643 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2644
2645 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2646 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002647 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002648 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002649 SourceLocation());
2650 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2651 Context->getPointerType(DRE->getType()),
2652 VK_RValue, OK_Ordinary,
2653 SourceLocation());
2654 // cast to NSConstantString *
2655 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2656 CK_CPointerToObjCPointerCast, Unop);
2657 ReplaceStmt(Exp, cast);
2658 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2659 return cast;
2660}
2661
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002662Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2663 unsigned IntSize =
2664 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2665
2666 Expr *FlagExp = IntegerLiteral::Create(*Context,
2667 llvm::APInt(IntSize, Exp->getValue()),
2668 Context->IntTy, Exp->getLocation());
2669 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2670 CK_BitCast, FlagExp);
2671 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2672 cast);
2673 ReplaceStmt(Exp, PE);
2674 return PE;
2675}
2676
Patrick Beard0caa3942012-04-19 00:25:12 +00002677Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002678 // synthesize declaration of helper functions needed in this routine.
2679 if (!SelGetUidFunctionDecl)
2680 SynthSelGetUidFunctionDecl();
2681 // use objc_msgSend() for all.
2682 if (!MsgSendFunctionDecl)
2683 SynthMsgSendFunctionDecl();
2684 if (!GetClassFunctionDecl)
2685 SynthGetClassFunctionDecl();
2686
2687 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2688 SourceLocation StartLoc = Exp->getLocStart();
2689 SourceLocation EndLoc = Exp->getLocEnd();
2690
2691 // Synthesize a call to objc_msgSend().
2692 SmallVector<Expr*, 4> MsgExprs;
2693 SmallVector<Expr*, 4> ClsExprs;
2694 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002695
Patrick Beard0caa3942012-04-19 00:25:12 +00002696 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2697 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2698 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002699
Patrick Beard0caa3942012-04-19 00:25:12 +00002700 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002701 ClsExprs.push_back(StringLiteral::Create(*Context,
2702 clsName->getName(),
2703 StringLiteral::Ascii, false,
2704 argType, SourceLocation()));
2705 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2706 &ClsExprs[0],
2707 ClsExprs.size(),
2708 StartLoc, EndLoc);
2709 MsgExprs.push_back(Cls);
2710
Patrick Beard0caa3942012-04-19 00:25:12 +00002711 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002712 // it will be the 2nd argument.
2713 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002714 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002715 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002716 StringLiteral::Ascii, false,
2717 argType, SourceLocation()));
2718 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2719 &SelExprs[0], SelExprs.size(),
2720 StartLoc, EndLoc);
2721 MsgExprs.push_back(SelExp);
2722
Patrick Beard0caa3942012-04-19 00:25:12 +00002723 // User provided sub-expression is the 3rd, and last, argument.
2724 Expr *subExpr = Exp->getSubExpr();
2725 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002726 QualType type = ICE->getType();
2727 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2728 CastKind CK = CK_BitCast;
2729 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2730 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002731 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002732 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002733 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002734
2735 SmallVector<QualType, 4> ArgTypes;
2736 ArgTypes.push_back(Context->getObjCIdType());
2737 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002738 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2739 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002740 ArgTypes.push_back((*PI)->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002741
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002742 QualType returnType = Exp->getType();
2743 // Get the type, we will need to reference it in a couple spots.
2744 QualType msgSendType = MsgSendFlavor->getType();
2745
2746 // Create a reference to the objc_msgSend() declaration.
2747 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2748 VK_LValue, SourceLocation());
2749
2750 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002751 Context->getPointerType(Context->VoidTy),
2752 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002753
2754 // Now do the "normal" pointer to function cast.
2755 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002756 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002757 castType = Context->getPointerType(castType);
2758 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2759 cast);
2760
2761 // Don't forget the parens to enforce the proper binding.
2762 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2763
2764 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00002765 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002766 FT->getResultType(), VK_RValue,
2767 EndLoc);
2768 ReplaceStmt(Exp, CE);
2769 return CE;
2770}
2771
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002772Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2773 // synthesize declaration of helper functions needed in this routine.
2774 if (!SelGetUidFunctionDecl)
2775 SynthSelGetUidFunctionDecl();
2776 // use objc_msgSend() for all.
2777 if (!MsgSendFunctionDecl)
2778 SynthMsgSendFunctionDecl();
2779 if (!GetClassFunctionDecl)
2780 SynthGetClassFunctionDecl();
2781
2782 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2783 SourceLocation StartLoc = Exp->getLocStart();
2784 SourceLocation EndLoc = Exp->getLocEnd();
2785
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002786 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002787 QualType IntQT = Context->IntTy;
2788 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002789 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002790 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002791 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2792 DeclRefExpr *NSArrayDRE =
2793 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2794 SourceLocation());
2795
2796 SmallVector<Expr*, 16> InitExprs;
2797 unsigned NumElements = Exp->getNumElements();
2798 unsigned UnsignedIntSize =
2799 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2800 Expr *count = IntegerLiteral::Create(*Context,
2801 llvm::APInt(UnsignedIntSize, NumElements),
2802 Context->UnsignedIntTy, SourceLocation());
2803 InitExprs.push_back(count);
2804 for (unsigned i = 0; i < NumElements; i++)
2805 InitExprs.push_back(Exp->getElement(i));
2806 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002807 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002808 NSArrayFType, VK_LValue, SourceLocation());
2809
2810 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2811 SourceLocation(),
2812 &Context->Idents.get("arr"),
2813 Context->getPointerType(Context->VoidPtrTy), 0,
2814 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002815 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002816 MemberExpr *ArrayLiteralME =
2817 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2818 SourceLocation(),
2819 ARRFD->getType(), VK_LValue,
2820 OK_Ordinary);
2821 QualType ConstIdT = Context->getObjCIdType().withConst();
2822 CStyleCastExpr * ArrayLiteralObjects =
2823 NoTypeInfoCStyleCastExpr(Context,
2824 Context->getPointerType(ConstIdT),
2825 CK_BitCast,
2826 ArrayLiteralME);
2827
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002828 // Synthesize a call to objc_msgSend().
2829 SmallVector<Expr*, 32> MsgExprs;
2830 SmallVector<Expr*, 4> ClsExprs;
2831 QualType argType = Context->getPointerType(Context->CharTy);
2832 QualType expType = Exp->getType();
2833
2834 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2835 ObjCInterfaceDecl *Class =
2836 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2837
2838 IdentifierInfo *clsName = Class->getIdentifier();
2839 ClsExprs.push_back(StringLiteral::Create(*Context,
2840 clsName->getName(),
2841 StringLiteral::Ascii, false,
2842 argType, SourceLocation()));
2843 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2844 &ClsExprs[0],
2845 ClsExprs.size(),
2846 StartLoc, EndLoc);
2847 MsgExprs.push_back(Cls);
2848
2849 // Create a call to sel_registerName("arrayWithObjects:count:").
2850 // it will be the 2nd argument.
2851 SmallVector<Expr*, 4> SelExprs;
2852 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2853 SelExprs.push_back(StringLiteral::Create(*Context,
2854 ArrayMethod->getSelector().getAsString(),
2855 StringLiteral::Ascii, false,
2856 argType, SourceLocation()));
2857 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2858 &SelExprs[0], SelExprs.size(),
2859 StartLoc, EndLoc);
2860 MsgExprs.push_back(SelExp);
2861
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002862 // (const id [])objects
2863 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002864
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002865 // (NSUInteger)cnt
2866 Expr *cnt = IntegerLiteral::Create(*Context,
2867 llvm::APInt(UnsignedIntSize, NumElements),
2868 Context->UnsignedIntTy, SourceLocation());
2869 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002870
2871
2872 SmallVector<QualType, 4> ArgTypes;
2873 ArgTypes.push_back(Context->getObjCIdType());
2874 ArgTypes.push_back(Context->getObjCSelType());
2875 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2876 E = ArrayMethod->param_end(); PI != E; ++PI)
2877 ArgTypes.push_back((*PI)->getType());
2878
2879 QualType returnType = Exp->getType();
2880 // Get the type, we will need to reference it in a couple spots.
2881 QualType msgSendType = MsgSendFlavor->getType();
2882
2883 // Create a reference to the objc_msgSend() declaration.
2884 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2885 VK_LValue, SourceLocation());
2886
2887 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2888 Context->getPointerType(Context->VoidTy),
2889 CK_BitCast, DRE);
2890
2891 // Now do the "normal" pointer to function cast.
2892 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002893 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002894 castType = Context->getPointerType(castType);
2895 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2896 cast);
2897
2898 // Don't forget the parens to enforce the proper binding.
2899 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2900
2901 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00002902 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002903 FT->getResultType(), VK_RValue,
2904 EndLoc);
2905 ReplaceStmt(Exp, CE);
2906 return CE;
2907}
2908
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002909Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2910 // synthesize declaration of helper functions needed in this routine.
2911 if (!SelGetUidFunctionDecl)
2912 SynthSelGetUidFunctionDecl();
2913 // use objc_msgSend() for all.
2914 if (!MsgSendFunctionDecl)
2915 SynthMsgSendFunctionDecl();
2916 if (!GetClassFunctionDecl)
2917 SynthGetClassFunctionDecl();
2918
2919 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2920 SourceLocation StartLoc = Exp->getLocStart();
2921 SourceLocation EndLoc = Exp->getLocEnd();
2922
2923 // Build the expression: __NSContainer_literal(int, ...).arr
2924 QualType IntQT = Context->IntTy;
2925 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002926 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002927 std::string NSDictFName("__NSContainer_literal");
2928 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2929 DeclRefExpr *NSDictDRE =
2930 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2931 SourceLocation());
2932
2933 SmallVector<Expr*, 16> KeyExprs;
2934 SmallVector<Expr*, 16> ValueExprs;
2935
2936 unsigned NumElements = Exp->getNumElements();
2937 unsigned UnsignedIntSize =
2938 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2939 Expr *count = IntegerLiteral::Create(*Context,
2940 llvm::APInt(UnsignedIntSize, NumElements),
2941 Context->UnsignedIntTy, SourceLocation());
2942 KeyExprs.push_back(count);
2943 ValueExprs.push_back(count);
2944 for (unsigned i = 0; i < NumElements; i++) {
2945 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2946 KeyExprs.push_back(Element.Key);
2947 ValueExprs.push_back(Element.Value);
2948 }
2949
2950 // (const id [])objects
2951 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002952 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002953 NSDictFType, VK_LValue, SourceLocation());
2954
2955 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2956 SourceLocation(),
2957 &Context->Idents.get("arr"),
2958 Context->getPointerType(Context->VoidPtrTy), 0,
2959 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002960 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002961 MemberExpr *DictLiteralValueME =
2962 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2963 SourceLocation(),
2964 ARRFD->getType(), VK_LValue,
2965 OK_Ordinary);
2966 QualType ConstIdT = Context->getObjCIdType().withConst();
2967 CStyleCastExpr * DictValueObjects =
2968 NoTypeInfoCStyleCastExpr(Context,
2969 Context->getPointerType(ConstIdT),
2970 CK_BitCast,
2971 DictLiteralValueME);
2972 // (const id <NSCopying> [])keys
2973 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002974 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002975 NSDictFType, VK_LValue, SourceLocation());
2976
2977 MemberExpr *DictLiteralKeyME =
2978 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2979 SourceLocation(),
2980 ARRFD->getType(), VK_LValue,
2981 OK_Ordinary);
2982
2983 CStyleCastExpr * DictKeyObjects =
2984 NoTypeInfoCStyleCastExpr(Context,
2985 Context->getPointerType(ConstIdT),
2986 CK_BitCast,
2987 DictLiteralKeyME);
2988
2989
2990
2991 // Synthesize a call to objc_msgSend().
2992 SmallVector<Expr*, 32> MsgExprs;
2993 SmallVector<Expr*, 4> ClsExprs;
2994 QualType argType = Context->getPointerType(Context->CharTy);
2995 QualType expType = Exp->getType();
2996
2997 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2998 ObjCInterfaceDecl *Class =
2999 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
3000
3001 IdentifierInfo *clsName = Class->getIdentifier();
3002 ClsExprs.push_back(StringLiteral::Create(*Context,
3003 clsName->getName(),
3004 StringLiteral::Ascii, false,
3005 argType, SourceLocation()));
3006 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3007 &ClsExprs[0],
3008 ClsExprs.size(),
3009 StartLoc, EndLoc);
3010 MsgExprs.push_back(Cls);
3011
3012 // Create a call to sel_registerName("arrayWithObjects:count:").
3013 // it will be the 2nd argument.
3014 SmallVector<Expr*, 4> SelExprs;
3015 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
3016 SelExprs.push_back(StringLiteral::Create(*Context,
3017 DictMethod->getSelector().getAsString(),
3018 StringLiteral::Ascii, false,
3019 argType, SourceLocation()));
3020 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3021 &SelExprs[0], SelExprs.size(),
3022 StartLoc, EndLoc);
3023 MsgExprs.push_back(SelExp);
3024
3025 // (const id [])objects
3026 MsgExprs.push_back(DictValueObjects);
3027
3028 // (const id <NSCopying> [])keys
3029 MsgExprs.push_back(DictKeyObjects);
3030
3031 // (NSUInteger)cnt
3032 Expr *cnt = IntegerLiteral::Create(*Context,
3033 llvm::APInt(UnsignedIntSize, NumElements),
3034 Context->UnsignedIntTy, SourceLocation());
3035 MsgExprs.push_back(cnt);
3036
3037
3038 SmallVector<QualType, 8> ArgTypes;
3039 ArgTypes.push_back(Context->getObjCIdType());
3040 ArgTypes.push_back(Context->getObjCSelType());
3041 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3042 E = DictMethod->param_end(); PI != E; ++PI) {
3043 QualType T = (*PI)->getType();
3044 if (const PointerType* PT = T->getAs<PointerType>()) {
3045 QualType PointeeTy = PT->getPointeeType();
3046 convertToUnqualifiedObjCType(PointeeTy);
3047 T = Context->getPointerType(PointeeTy);
3048 }
3049 ArgTypes.push_back(T);
3050 }
3051
3052 QualType returnType = Exp->getType();
3053 // Get the type, we will need to reference it in a couple spots.
3054 QualType msgSendType = MsgSendFlavor->getType();
3055
3056 // Create a reference to the objc_msgSend() declaration.
3057 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3058 VK_LValue, SourceLocation());
3059
3060 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3061 Context->getPointerType(Context->VoidTy),
3062 CK_BitCast, DRE);
3063
3064 // Now do the "normal" pointer to function cast.
3065 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003066 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003067 castType = Context->getPointerType(castType);
3068 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3069 cast);
3070
3071 // Don't forget the parens to enforce the proper binding.
3072 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3073
3074 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00003075 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003076 FT->getResultType(), VK_RValue,
3077 EndLoc);
3078 ReplaceStmt(Exp, CE);
3079 return CE;
3080}
3081
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003082// struct __rw_objc_super {
3083// struct objc_object *object; struct objc_object *superClass;
3084// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003085QualType RewriteModernObjC::getSuperStructType() {
3086 if (!SuperStructDecl) {
3087 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3088 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003089 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003090 QualType FieldTypes[2];
3091
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003092 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003093 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003094 // struct objc_object *superClass;
3095 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003096
3097 // Create fields
3098 for (unsigned i = 0; i < 2; ++i) {
3099 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3100 SourceLocation(),
3101 SourceLocation(), 0,
3102 FieldTypes[i], 0,
3103 /*BitWidth=*/0,
3104 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003105 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003106 }
3107
3108 SuperStructDecl->completeDefinition();
3109 }
3110 return Context->getTagDeclType(SuperStructDecl);
3111}
3112
3113QualType RewriteModernObjC::getConstantStringStructType() {
3114 if (!ConstantStringDecl) {
3115 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3116 SourceLocation(), SourceLocation(),
3117 &Context->Idents.get("__NSConstantStringImpl"));
3118 QualType FieldTypes[4];
3119
3120 // struct objc_object *receiver;
3121 FieldTypes[0] = Context->getObjCIdType();
3122 // int flags;
3123 FieldTypes[1] = Context->IntTy;
3124 // char *str;
3125 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3126 // long length;
3127 FieldTypes[3] = Context->LongTy;
3128
3129 // Create fields
3130 for (unsigned i = 0; i < 4; ++i) {
3131 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3132 ConstantStringDecl,
3133 SourceLocation(),
3134 SourceLocation(), 0,
3135 FieldTypes[i], 0,
3136 /*BitWidth=*/0,
3137 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003138 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003139 }
3140
3141 ConstantStringDecl->completeDefinition();
3142 }
3143 return Context->getTagDeclType(ConstantStringDecl);
3144}
3145
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003146/// getFunctionSourceLocation - returns start location of a function
3147/// definition. Complication arises when function has declared as
3148/// extern "C" or extern "C" {...}
3149static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3150 FunctionDecl *FD) {
3151 if (FD->isExternC() && !FD->isMain()) {
3152 const DeclContext *DC = FD->getDeclContext();
3153 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3154 // if it is extern "C" {...}, return function decl's own location.
3155 if (!LSD->getRBraceLoc().isValid())
3156 return LSD->getExternLoc();
3157 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003158 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003159 R.RewriteBlockLiteralFunctionDecl(FD);
3160 return FD->getTypeSpecStartLoc();
3161}
3162
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003163void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3164
3165 SourceLocation Location = D->getLocation();
3166
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003167 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003168 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003169 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3170 LineString += utostr(PLoc.getLine());
3171 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003172 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003173 if (isa<ObjCMethodDecl>(D))
3174 LineString += "\"";
3175 else LineString += "\"\n";
3176
3177 Location = D->getLocStart();
3178 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3179 if (FD->isExternC() && !FD->isMain()) {
3180 const DeclContext *DC = FD->getDeclContext();
3181 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3182 // if it is extern "C" {...}, return function decl's own location.
3183 if (!LSD->getRBraceLoc().isValid())
3184 Location = LSD->getExternLoc();
3185 }
3186 }
3187 InsertText(Location, LineString);
3188 }
3189}
3190
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003191/// SynthMsgSendStretCallExpr - This routine translates message expression
3192/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3193/// nil check on receiver must be performed before calling objc_msgSend_stret.
3194/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3195/// msgSendType - function type of objc_msgSend_stret(...)
3196/// returnType - Result type of the method being synthesized.
3197/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3198/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3199/// starting with receiver.
3200/// Method - Method being rewritten.
3201Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003202 QualType returnType,
3203 SmallVectorImpl<QualType> &ArgTypes,
3204 SmallVectorImpl<Expr*> &MsgExprs,
3205 ObjCMethodDecl *Method) {
3206 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003207 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3208 Method ? Method->isVariadic()
3209 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003210 castType = Context->getPointerType(castType);
3211
3212 // build type for containing the objc_msgSend_stret object.
3213 static unsigned stretCount=0;
3214 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003215 std::string str =
3216 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003217 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003218 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003219 str += " {\n\t";
3220 str += name;
3221 str += "(id receiver, SEL sel";
3222 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003223 std::string ArgName = "arg"; ArgName += utostr(i);
3224 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3225 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003226 }
3227 // could be vararg.
3228 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003229 std::string ArgName = "arg"; ArgName += utostr(i);
3230 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3231 Context->getPrintingPolicy());
3232 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003233 }
3234
3235 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003236 str += "\t unsigned size = sizeof(";
3237 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3238
3239 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3240
3241 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3242 str += ")(void *)objc_msgSend)(receiver, sel";
3243 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3244 str += ", arg"; str += utostr(i);
3245 }
3246 // could be vararg.
3247 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3248 str += ", arg"; str += utostr(i);
3249 }
3250 str+= ");\n";
3251
3252 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003253 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3254 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003255
3256
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003257 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3258 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3259 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3260 str += ", arg"; str += utostr(i);
3261 }
3262 // could be vararg.
3263 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3264 str += ", arg"; str += utostr(i);
3265 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003266 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003267
3268
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003269 str += "\t}\n";
3270 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3271 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003272 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003273 SourceLocation FunLocStart;
3274 if (CurFunctionDef)
3275 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3276 else {
3277 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3278 FunLocStart = CurMethodDef->getLocStart();
3279 }
3280
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003281 InsertText(FunLocStart, str);
3282 ++stretCount;
3283
3284 // AST for __Stretn(receiver, args).s;
3285 IdentifierInfo *ID = &Context->Idents.get(name);
3286 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003287 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003288 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003289 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3290 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003291 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003292 castType, VK_LValue, SourceLocation());
3293
3294 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3295 SourceLocation(),
3296 &Context->Idents.get("s"),
3297 returnType, 0,
3298 /*BitWidth=*/0, /*Mutable=*/true,
3299 ICIS_NoInit);
3300 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3301 FieldD->getType(), VK_LValue,
3302 OK_Ordinary);
3303
3304 return ME;
3305}
3306
Fariborz Jahanian11671902012-02-07 17:11:38 +00003307Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3308 SourceLocation StartLoc,
3309 SourceLocation EndLoc) {
3310 if (!SelGetUidFunctionDecl)
3311 SynthSelGetUidFunctionDecl();
3312 if (!MsgSendFunctionDecl)
3313 SynthMsgSendFunctionDecl();
3314 if (!MsgSendSuperFunctionDecl)
3315 SynthMsgSendSuperFunctionDecl();
3316 if (!MsgSendStretFunctionDecl)
3317 SynthMsgSendStretFunctionDecl();
3318 if (!MsgSendSuperStretFunctionDecl)
3319 SynthMsgSendSuperStretFunctionDecl();
3320 if (!MsgSendFpretFunctionDecl)
3321 SynthMsgSendFpretFunctionDecl();
3322 if (!GetClassFunctionDecl)
3323 SynthGetClassFunctionDecl();
3324 if (!GetSuperClassFunctionDecl)
3325 SynthGetSuperClassFunctionDecl();
3326 if (!GetMetaClassFunctionDecl)
3327 SynthGetMetaClassFunctionDecl();
3328
3329 // default to objc_msgSend().
3330 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3331 // May need to use objc_msgSend_stret() as well.
3332 FunctionDecl *MsgSendStretFlavor = 0;
3333 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3334 QualType resultType = mDecl->getResultType();
3335 if (resultType->isRecordType())
3336 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3337 else if (resultType->isRealFloatingType())
3338 MsgSendFlavor = MsgSendFpretFunctionDecl;
3339 }
3340
3341 // Synthesize a call to objc_msgSend().
3342 SmallVector<Expr*, 8> MsgExprs;
3343 switch (Exp->getReceiverKind()) {
3344 case ObjCMessageExpr::SuperClass: {
3345 MsgSendFlavor = MsgSendSuperFunctionDecl;
3346 if (MsgSendStretFlavor)
3347 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3348 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3349
3350 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3351
3352 SmallVector<Expr*, 4> InitExprs;
3353
3354 // set the receiver to self, the first argument to all methods.
3355 InitExprs.push_back(
3356 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3357 CK_BitCast,
3358 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003359 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003360 Context->getObjCIdType(),
3361 VK_RValue,
3362 SourceLocation()))
3363 ); // set the 'receiver'.
3364
3365 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3366 SmallVector<Expr*, 8> ClsExprs;
3367 QualType argType = Context->getPointerType(Context->CharTy);
3368 ClsExprs.push_back(StringLiteral::Create(*Context,
3369 ClassDecl->getIdentifier()->getName(),
3370 StringLiteral::Ascii, false,
3371 argType, SourceLocation()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003372 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003373 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3374 &ClsExprs[0],
3375 ClsExprs.size(),
3376 StartLoc,
3377 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003378 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003379 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003380 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3381 &ClsExprs[0], ClsExprs.size(),
3382 StartLoc, EndLoc);
3383
3384 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3385 // To turn off a warning, type-cast to 'id'
3386 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3387 NoTypeInfoCStyleCastExpr(Context,
3388 Context->getObjCIdType(),
3389 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003390 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003391 QualType superType = getSuperStructType();
3392 Expr *SuperRep;
3393
3394 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003395 SynthSuperConstructorFunctionDecl();
3396 // Simulate a constructor call...
3397 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003398 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003399 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003400 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003401 superType, VK_LValue,
3402 SourceLocation());
3403 // The code for super is a little tricky to prevent collision with
3404 // the structure definition in the header. The rewriter has it's own
3405 // internal definition (__rw_objc_super) that is uses. This is why
3406 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003407 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003408 //
3409 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3410 Context->getPointerType(SuperRep->getType()),
3411 VK_RValue, OK_Ordinary,
3412 SourceLocation());
3413 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3414 Context->getPointerType(superType),
3415 CK_BitCast, SuperRep);
3416 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003417 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003418 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003419 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003420 SourceLocation());
3421 TypeSourceInfo *superTInfo
3422 = Context->getTrivialTypeSourceInfo(superType);
3423 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3424 superType, VK_LValue,
3425 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003426 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003427 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3428 Context->getPointerType(SuperRep->getType()),
3429 VK_RValue, OK_Ordinary,
3430 SourceLocation());
3431 }
3432 MsgExprs.push_back(SuperRep);
3433 break;
3434 }
3435
3436 case ObjCMessageExpr::Class: {
3437 SmallVector<Expr*, 8> ClsExprs;
3438 QualType argType = Context->getPointerType(Context->CharTy);
3439 ObjCInterfaceDecl *Class
3440 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3441 IdentifierInfo *clsName = Class->getIdentifier();
3442 ClsExprs.push_back(StringLiteral::Create(*Context,
3443 clsName->getName(),
3444 StringLiteral::Ascii, false,
3445 argType, SourceLocation()));
3446 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3447 &ClsExprs[0],
3448 ClsExprs.size(),
3449 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003450 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3451 Context->getObjCIdType(),
3452 CK_BitCast, Cls);
3453 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003454 break;
3455 }
3456
3457 case ObjCMessageExpr::SuperInstance:{
3458 MsgSendFlavor = MsgSendSuperFunctionDecl;
3459 if (MsgSendStretFlavor)
3460 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3461 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3462 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3463 SmallVector<Expr*, 4> InitExprs;
3464
3465 InitExprs.push_back(
3466 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3467 CK_BitCast,
3468 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003469 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003470 Context->getObjCIdType(),
3471 VK_RValue, SourceLocation()))
3472 ); // set the 'receiver'.
3473
3474 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3475 SmallVector<Expr*, 8> ClsExprs;
3476 QualType argType = Context->getPointerType(Context->CharTy);
3477 ClsExprs.push_back(StringLiteral::Create(*Context,
3478 ClassDecl->getIdentifier()->getName(),
3479 StringLiteral::Ascii, false, argType,
3480 SourceLocation()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003481 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003482 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3483 &ClsExprs[0],
3484 ClsExprs.size(),
3485 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003486 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003487 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003488 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3489 &ClsExprs[0], ClsExprs.size(),
3490 StartLoc, EndLoc);
3491
3492 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3493 // To turn off a warning, type-cast to 'id'
3494 InitExprs.push_back(
3495 // set 'super class', using class_getSuperclass().
3496 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3497 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003498 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003499 QualType superType = getSuperStructType();
3500 Expr *SuperRep;
3501
3502 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003503 SynthSuperConstructorFunctionDecl();
3504 // Simulate a constructor call...
3505 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003506 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003507 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003508 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003509 superType, VK_LValue, SourceLocation());
3510 // The code for super is a little tricky to prevent collision with
3511 // the structure definition in the header. The rewriter has it's own
3512 // internal definition (__rw_objc_super) that is uses. This is why
3513 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003514 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003515 //
3516 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3517 Context->getPointerType(SuperRep->getType()),
3518 VK_RValue, OK_Ordinary,
3519 SourceLocation());
3520 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3521 Context->getPointerType(superType),
3522 CK_BitCast, SuperRep);
3523 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003524 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003525 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003526 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003527 SourceLocation());
3528 TypeSourceInfo *superTInfo
3529 = Context->getTrivialTypeSourceInfo(superType);
3530 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3531 superType, VK_RValue, ILE,
3532 false);
3533 }
3534 MsgExprs.push_back(SuperRep);
3535 break;
3536 }
3537
3538 case ObjCMessageExpr::Instance: {
3539 // Remove all type-casts because it may contain objc-style types; e.g.
3540 // Foo<Proto> *.
3541 Expr *recExpr = Exp->getInstanceReceiver();
3542 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3543 recExpr = CE->getSubExpr();
3544 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3545 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3546 ? CK_BlockPointerToObjCPointerCast
3547 : CK_CPointerToObjCPointerCast;
3548
3549 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3550 CK, recExpr);
3551 MsgExprs.push_back(recExpr);
3552 break;
3553 }
3554 }
3555
3556 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3557 SmallVector<Expr*, 8> SelExprs;
3558 QualType argType = Context->getPointerType(Context->CharTy);
3559 SelExprs.push_back(StringLiteral::Create(*Context,
3560 Exp->getSelector().getAsString(),
3561 StringLiteral::Ascii, false,
3562 argType, SourceLocation()));
3563 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3564 &SelExprs[0], SelExprs.size(),
3565 StartLoc,
3566 EndLoc);
3567 MsgExprs.push_back(SelExp);
3568
3569 // Now push any user supplied arguments.
3570 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3571 Expr *userExpr = Exp->getArg(i);
3572 // Make all implicit casts explicit...ICE comes in handy:-)
3573 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3574 // Reuse the ICE type, it is exactly what the doctor ordered.
3575 QualType type = ICE->getType();
3576 if (needToScanForQualifiers(type))
3577 type = Context->getObjCIdType();
3578 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3579 (void)convertBlockPointerToFunctionPointer(type);
3580 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3581 CastKind CK;
3582 if (SubExpr->getType()->isIntegralType(*Context) &&
3583 type->isBooleanType()) {
3584 CK = CK_IntegralToBoolean;
3585 } else if (type->isObjCObjectPointerType()) {
3586 if (SubExpr->getType()->isBlockPointerType()) {
3587 CK = CK_BlockPointerToObjCPointerCast;
3588 } else if (SubExpr->getType()->isPointerType()) {
3589 CK = CK_CPointerToObjCPointerCast;
3590 } else {
3591 CK = CK_BitCast;
3592 }
3593 } else {
3594 CK = CK_BitCast;
3595 }
3596
3597 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3598 }
3599 // Make id<P...> cast into an 'id' cast.
3600 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3601 if (CE->getType()->isObjCQualifiedIdType()) {
3602 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3603 userExpr = CE->getSubExpr();
3604 CastKind CK;
3605 if (userExpr->getType()->isIntegralType(*Context)) {
3606 CK = CK_IntegralToPointer;
3607 } else if (userExpr->getType()->isBlockPointerType()) {
3608 CK = CK_BlockPointerToObjCPointerCast;
3609 } else if (userExpr->getType()->isPointerType()) {
3610 CK = CK_CPointerToObjCPointerCast;
3611 } else {
3612 CK = CK_BitCast;
3613 }
3614 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3615 CK, userExpr);
3616 }
3617 }
3618 MsgExprs.push_back(userExpr);
3619 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3620 // out the argument in the original expression (since we aren't deleting
3621 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3622 //Exp->setArg(i, 0);
3623 }
3624 // Generate the funky cast.
3625 CastExpr *cast;
3626 SmallVector<QualType, 8> ArgTypes;
3627 QualType returnType;
3628
3629 // Push 'id' and 'SEL', the 2 implicit arguments.
3630 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3631 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3632 else
3633 ArgTypes.push_back(Context->getObjCIdType());
3634 ArgTypes.push_back(Context->getObjCSelType());
3635 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3636 // Push any user argument types.
3637 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3638 E = OMD->param_end(); PI != E; ++PI) {
3639 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3640 ? Context->getObjCIdType()
3641 : (*PI)->getType();
3642 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3643 (void)convertBlockPointerToFunctionPointer(t);
3644 ArgTypes.push_back(t);
3645 }
3646 returnType = Exp->getType();
3647 convertToUnqualifiedObjCType(returnType);
3648 (void)convertBlockPointerToFunctionPointer(returnType);
3649 } else {
3650 returnType = Context->getObjCIdType();
3651 }
3652 // Get the type, we will need to reference it in a couple spots.
3653 QualType msgSendType = MsgSendFlavor->getType();
3654
3655 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003656 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003657 VK_LValue, SourceLocation());
3658
3659 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3660 // If we don't do this cast, we get the following bizarre warning/note:
3661 // xx.m:13: warning: function called through a non-compatible type
3662 // xx.m:13: note: if this code is reached, the program will abort
3663 cast = NoTypeInfoCStyleCastExpr(Context,
3664 Context->getPointerType(Context->VoidTy),
3665 CK_BitCast, DRE);
3666
3667 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003668 // If we don't have a method decl, force a variadic cast.
3669 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003670 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003671 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003672 castType = Context->getPointerType(castType);
3673 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3674 cast);
3675
3676 // Don't forget the parens to enforce the proper binding.
3677 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3678
3679 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00003680 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3681 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003682 Stmt *ReplacingStmt = CE;
3683 if (MsgSendStretFlavor) {
3684 // We have the method which returns a struct/union. Must also generate
3685 // call to objc_msgSend_stret and hang both varieties on a conditional
3686 // expression which dictate which one to envoke depending on size of
3687 // method's return type.
3688
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003689 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3690 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003691 ArgTypes, MsgExprs,
3692 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003693 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003694 }
3695 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3696 return ReplacingStmt;
3697}
3698
3699Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3700 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3701 Exp->getLocEnd());
3702
3703 // Now do the actual rewrite.
3704 ReplaceStmt(Exp, ReplacingStmt);
3705
3706 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3707 return ReplacingStmt;
3708}
3709
3710// typedef struct objc_object Protocol;
3711QualType RewriteModernObjC::getProtocolType() {
3712 if (!ProtocolTypeDecl) {
3713 TypeSourceInfo *TInfo
3714 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3715 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3716 SourceLocation(), SourceLocation(),
3717 &Context->Idents.get("Protocol"),
3718 TInfo);
3719 }
3720 return Context->getTypeDeclType(ProtocolTypeDecl);
3721}
3722
3723/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3724/// a synthesized/forward data reference (to the protocol's metadata).
3725/// The forward references (and metadata) are generated in
3726/// RewriteModernObjC::HandleTranslationUnit().
3727Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003728 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3729 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003730 IdentifierInfo *ID = &Context->Idents.get(Name);
3731 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3732 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003733 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003734 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3735 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003736 CastExpr *castExpr =
3737 NoTypeInfoCStyleCastExpr(
3738 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003739 ReplaceStmt(Exp, castExpr);
3740 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3741 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3742 return castExpr;
3743
3744}
3745
3746bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3747 const char *endBuf) {
3748 while (startBuf < endBuf) {
3749 if (*startBuf == '#') {
3750 // Skip whitespace.
3751 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3752 ;
3753 if (!strncmp(startBuf, "if", strlen("if")) ||
3754 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3755 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3756 !strncmp(startBuf, "define", strlen("define")) ||
3757 !strncmp(startBuf, "undef", strlen("undef")) ||
3758 !strncmp(startBuf, "else", strlen("else")) ||
3759 !strncmp(startBuf, "elif", strlen("elif")) ||
3760 !strncmp(startBuf, "endif", strlen("endif")) ||
3761 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3762 !strncmp(startBuf, "include", strlen("include")) ||
3763 !strncmp(startBuf, "import", strlen("import")) ||
3764 !strncmp(startBuf, "include_next", strlen("include_next")))
3765 return true;
3766 }
3767 startBuf++;
3768 }
3769 return false;
3770}
3771
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003772/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3773/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003774bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003775 TagDecl *Tag,
3776 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003777 if (!IDecl)
3778 return false;
3779 SourceLocation TagLocation;
3780 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3781 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003782 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003783 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003784 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003785 TagLocation = RD->getLocation();
3786 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003787 IDecl->getLocation(), TagLocation);
3788 }
3789 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3790 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3791 return false;
3792 IsNamedDefinition = true;
3793 TagLocation = ED->getLocation();
3794 return Context->getSourceManager().isBeforeInTranslationUnit(
3795 IDecl->getLocation(), TagLocation);
3796
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003797 }
3798 return false;
3799}
3800
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003801/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003802/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003803bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3804 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003805 if (isa<TypedefType>(Type)) {
3806 Result += "\t";
3807 return false;
3808 }
3809
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003810 if (Type->isArrayType()) {
3811 QualType ElemTy = Context->getBaseElementType(Type);
3812 return RewriteObjCFieldDeclType(ElemTy, Result);
3813 }
3814 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003815 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3816 if (RD->isCompleteDefinition()) {
3817 if (RD->isStruct())
3818 Result += "\n\tstruct ";
3819 else if (RD->isUnion())
3820 Result += "\n\tunion ";
3821 else
3822 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003823
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003824 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003825 if (GlobalDefinedTags.count(RD)) {
3826 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003827 Result += " ";
3828 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003829 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003830 Result += " {\n";
3831 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003832 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003833 FieldDecl *FD = *i;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003834 RewriteObjCFieldDecl(FD, Result);
3835 }
3836 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003837 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003838 }
3839 }
3840 else if (Type->isEnumeralType()) {
3841 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3842 if (ED->isCompleteDefinition()) {
3843 Result += "\n\tenum ";
3844 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003845 if (GlobalDefinedTags.count(ED)) {
3846 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003847 Result += " ";
3848 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003849 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003850
3851 Result += " {\n";
3852 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3853 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3854 Result += "\t"; Result += EC->getName(); Result += " = ";
3855 llvm::APSInt Val = EC->getInitVal();
3856 Result += Val.toString(10);
3857 Result += ",\n";
3858 }
3859 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003860 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003861 }
3862 }
3863
3864 Result += "\t";
3865 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003866 return false;
3867}
3868
3869
3870/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3871/// It handles elaborated types, as well as enum types in the process.
3872void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3873 std::string &Result) {
3874 QualType Type = fieldDecl->getType();
3875 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003876
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003877 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3878 if (!EleboratedType)
3879 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003880 Result += Name;
3881 if (fieldDecl->isBitField()) {
3882 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3883 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003884 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003885 const ArrayType *AT = Context->getAsArrayType(Type);
3886 do {
3887 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003888 Result += "[";
3889 llvm::APInt Dim = CAT->getSize();
3890 Result += utostr(Dim.getZExtValue());
3891 Result += "]";
3892 }
Eli Friedman07bab732012-12-13 01:43:21 +00003893 AT = Context->getAsArrayType(AT->getElementType());
3894 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003895 }
3896
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003897 Result += ";\n";
3898}
3899
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003900/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3901/// named aggregate types into the input buffer.
3902void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3903 std::string &Result) {
3904 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003905 if (isa<TypedefType>(Type))
3906 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003907 if (Type->isArrayType())
3908 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003909 ObjCContainerDecl *IDecl =
3910 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003911
3912 TagDecl *TD = 0;
3913 if (Type->isRecordType()) {
3914 TD = Type->getAs<RecordType>()->getDecl();
3915 }
3916 else if (Type->isEnumeralType()) {
3917 TD = Type->getAs<EnumType>()->getDecl();
3918 }
3919
3920 if (TD) {
3921 if (GlobalDefinedTags.count(TD))
3922 return;
3923
3924 bool IsNamedDefinition = false;
3925 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3926 RewriteObjCFieldDeclType(Type, Result);
3927 Result += ";";
3928 }
3929 if (IsNamedDefinition)
3930 GlobalDefinedTags.insert(TD);
3931 }
3932
3933}
3934
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003935unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3936 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3937 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3938 return IvarGroupNumber[IV];
3939 }
3940 unsigned GroupNo = 0;
3941 SmallVector<const ObjCIvarDecl *, 8> IVars;
3942 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3943 IVD; IVD = IVD->getNextIvar())
3944 IVars.push_back(IVD);
3945
3946 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3947 if (IVars[i]->isBitField()) {
3948 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3949 while (i < e && IVars[i]->isBitField())
3950 IvarGroupNumber[IVars[i++]] = GroupNo;
3951 if (i < e)
3952 --i;
3953 }
3954
3955 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3956 return IvarGroupNumber[IV];
3957}
3958
3959QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3960 ObjCIvarDecl *IV,
3961 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3962 std::string StructTagName;
3963 ObjCIvarBitfieldGroupType(IV, StructTagName);
3964 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3965 Context->getTranslationUnitDecl(),
3966 SourceLocation(), SourceLocation(),
3967 &Context->Idents.get(StructTagName));
3968 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3969 ObjCIvarDecl *Ivar = IVars[i];
3970 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3971 &Context->Idents.get(Ivar->getName()),
3972 Ivar->getType(),
3973 0, /*Expr *BW */Ivar->getBitWidth(), false,
3974 ICIS_NoInit));
3975 }
3976 RD->completeDefinition();
3977 return Context->getTagDeclType(RD);
3978}
3979
3980QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3981 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3982 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3983 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3984 if (GroupRecordType.count(tuple))
3985 return GroupRecordType[tuple];
3986
3987 SmallVector<ObjCIvarDecl *, 8> IVars;
3988 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3989 IVD; IVD = IVD->getNextIvar()) {
3990 if (IVD->isBitField())
3991 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3992 else {
3993 if (!IVars.empty()) {
3994 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3995 // Generate the struct type for this group of bitfield ivars.
3996 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3997 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3998 IVars.clear();
3999 }
4000 }
4001 }
4002 if (!IVars.empty()) {
4003 // Do the last one.
4004 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
4005 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4006 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4007 }
4008 QualType RetQT = GroupRecordType[tuple];
4009 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4010
4011 return RetQT;
4012}
4013
4014/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4015/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4016void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4017 std::string &Result) {
4018 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4019 Result += CDecl->getName();
4020 Result += "__GRBF_";
4021 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4022 Result += utostr(GroupNo);
4023 return;
4024}
4025
4026/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4027/// Name of the struct would be: classname__T_n where n is the group number for
4028/// this ivar.
4029void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4030 std::string &Result) {
4031 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4032 Result += CDecl->getName();
4033 Result += "__T_";
4034 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4035 Result += utostr(GroupNo);
4036 return;
4037}
4038
4039/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4040/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4041/// this ivar.
4042void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4043 std::string &Result) {
4044 Result += "OBJC_IVAR_$_";
4045 ObjCIvarBitfieldGroupDecl(IV, Result);
4046}
4047
4048#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4049 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4050 ++IX; \
4051 if (IX < ENDIX) \
4052 --IX; \
4053}
4054
Fariborz Jahanian11671902012-02-07 17:11:38 +00004055/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4056/// an objective-c class with ivars.
4057void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4058 std::string &Result) {
4059 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4060 assert(CDecl->getName() != "" &&
4061 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004062 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004063 SmallVector<ObjCIvarDecl *, 8> IVars;
4064 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004065 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004066 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004067
Fariborz Jahanian11671902012-02-07 17:11:38 +00004068 SourceLocation LocStart = CDecl->getLocStart();
4069 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004070
Fariborz Jahanian11671902012-02-07 17:11:38 +00004071 const char *startBuf = SM->getCharacterData(LocStart);
4072 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004073
Fariborz Jahanian11671902012-02-07 17:11:38 +00004074 // If no ivars and no root or if its root, directly or indirectly,
4075 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004076 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004077 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4078 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4079 ReplaceText(LocStart, endBuf-startBuf, Result);
4080 return;
4081 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004082
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004083 // Insert named struct/union definitions inside class to
4084 // outer scope. This follows semantics of locally defined
4085 // struct/unions in objective-c classes.
4086 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4087 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004088
4089 // Insert named structs which are syntheized to group ivar bitfields
4090 // to outer scope as well.
4091 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4092 if (IVars[i]->isBitField()) {
4093 ObjCIvarDecl *IV = IVars[i];
4094 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4095 RewriteObjCFieldDeclType(QT, Result);
4096 Result += ";";
4097 // skip over ivar bitfields in this group.
4098 SKIP_BITFIELDS(i , e, IVars);
4099 }
4100
Fariborz Jahanian11671902012-02-07 17:11:38 +00004101 Result += "\nstruct ";
4102 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004103 Result += "_IMPL {\n";
4104
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004105 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004106 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4107 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4108 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004109 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004110
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004111 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4112 if (IVars[i]->isBitField()) {
4113 ObjCIvarDecl *IV = IVars[i];
4114 Result += "\tstruct ";
4115 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4116 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4117 // skip over ivar bitfields in this group.
4118 SKIP_BITFIELDS(i , e, IVars);
4119 }
4120 else
4121 RewriteObjCFieldDecl(IVars[i], Result);
4122 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004123
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004124 Result += "};\n";
4125 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4126 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004127 // Mark this struct as having been generated.
4128 if (!ObjCSynthesizedStructs.insert(CDecl))
4129 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004130}
4131
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004132/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4133/// have been referenced in an ivar access expression.
4134void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4135 std::string &Result) {
4136 // write out ivar offset symbols which have been referenced in an ivar
4137 // access expression.
4138 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4139 if (Ivars.empty())
4140 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004141
4142 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004143 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4144 e = Ivars.end(); i != e; i++) {
4145 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004146 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4147 unsigned GroupNo = 0;
4148 if (IvarDecl->isBitField()) {
4149 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4150 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4151 continue;
4152 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004153 Result += "\n";
4154 if (LangOpts.MicrosoftExt)
4155 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004156 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004157 if (LangOpts.MicrosoftExt &&
4158 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004159 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4160 Result += "__declspec(dllimport) ";
4161
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004162 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004163 if (IvarDecl->isBitField()) {
4164 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4165 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4166 }
4167 else
4168 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004169 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004170 }
4171}
4172
Fariborz Jahanian11671902012-02-07 17:11:38 +00004173//===----------------------------------------------------------------------===//
4174// Meta Data Emission
4175//===----------------------------------------------------------------------===//
4176
4177
4178/// RewriteImplementations - This routine rewrites all method implementations
4179/// and emits meta-data.
4180
4181void RewriteModernObjC::RewriteImplementations() {
4182 int ClsDefCount = ClassImplementation.size();
4183 int CatDefCount = CategoryImplementation.size();
4184
4185 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004186 for (int i = 0; i < ClsDefCount; i++) {
4187 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4188 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4189 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004190 assert(false &&
4191 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004192 RewriteImplementationDecl(OIMP);
4193 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004194
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004195 for (int i = 0; i < CatDefCount; i++) {
4196 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4197 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4198 if (CDecl->isImplicitInterfaceDecl())
4199 assert(false &&
4200 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004201 RewriteImplementationDecl(CIMP);
4202 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004203}
4204
4205void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4206 const std::string &Name,
4207 ValueDecl *VD, bool def) {
4208 assert(BlockByRefDeclNo.count(VD) &&
4209 "RewriteByRefString: ByRef decl missing");
4210 if (def)
4211 ResultStr += "struct ";
4212 ResultStr += "__Block_byref_" + Name +
4213 "_" + utostr(BlockByRefDeclNo[VD]) ;
4214}
4215
4216static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4217 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4218 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4219 return false;
4220}
4221
4222std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4223 StringRef funcName,
4224 std::string Tag) {
4225 const FunctionType *AFT = CE->getFunctionType();
4226 QualType RT = AFT->getResultType();
4227 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004228 SourceLocation BlockLoc = CE->getExprLoc();
4229 std::string S;
4230 ConvertSourceLocationToLineDirective(BlockLoc, S);
4231
4232 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4233 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004234
4235 BlockDecl *BD = CE->getBlockDecl();
4236
4237 if (isa<FunctionNoProtoType>(AFT)) {
4238 // No user-supplied arguments. Still need to pass in a pointer to the
4239 // block (to reference imported block decl refs).
4240 S += "(" + StructRef + " *__cself)";
4241 } else if (BD->param_empty()) {
4242 S += "(" + StructRef + " *__cself)";
4243 } else {
4244 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4245 assert(FT && "SynthesizeBlockFunc: No function proto");
4246 S += '(';
4247 // first add the implicit argument.
4248 S += StructRef + " *__cself, ";
4249 std::string ParamStr;
4250 for (BlockDecl::param_iterator AI = BD->param_begin(),
4251 E = BD->param_end(); AI != E; ++AI) {
4252 if (AI != BD->param_begin()) S += ", ";
4253 ParamStr = (*AI)->getNameAsString();
4254 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004255 (void)convertBlockPointerToFunctionPointer(QT);
4256 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004257 S += ParamStr;
4258 }
4259 if (FT->isVariadic()) {
4260 if (!BD->param_empty()) S += ", ";
4261 S += "...";
4262 }
4263 S += ')';
4264 }
4265 S += " {\n";
4266
4267 // Create local declarations to avoid rewriting all closure decl ref exprs.
4268 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004269 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004270 E = BlockByRefDecls.end(); I != E; ++I) {
4271 S += " ";
4272 std::string Name = (*I)->getNameAsString();
4273 std::string TypeString;
4274 RewriteByRefString(TypeString, Name, (*I));
4275 TypeString += " *";
4276 Name = TypeString + Name;
4277 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4278 }
4279 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004280 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004281 E = BlockByCopyDecls.end(); I != E; ++I) {
4282 S += " ";
4283 // Handle nested closure invocation. For example:
4284 //
4285 // void (^myImportedClosure)(void);
4286 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4287 //
4288 // void (^anotherClosure)(void);
4289 // anotherClosure = ^(void) {
4290 // myImportedClosure(); // import and invoke the closure
4291 // };
4292 //
4293 if (isTopLevelBlockPointerType((*I)->getType())) {
4294 RewriteBlockPointerTypeVariable(S, (*I));
4295 S += " = (";
4296 RewriteBlockPointerType(S, (*I)->getType());
4297 S += ")";
4298 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4299 }
4300 else {
4301 std::string Name = (*I)->getNameAsString();
4302 QualType QT = (*I)->getType();
4303 if (HasLocalVariableExternalStorage(*I))
4304 QT = Context->getPointerType(QT);
4305 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4306 S += Name + " = __cself->" +
4307 (*I)->getNameAsString() + "; // bound by copy\n";
4308 }
4309 }
4310 std::string RewrittenStr = RewrittenBlockExprs[CE];
4311 const char *cstr = RewrittenStr.c_str();
4312 while (*cstr++ != '{') ;
4313 S += cstr;
4314 S += "\n";
4315 return S;
4316}
4317
4318std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4319 StringRef funcName,
4320 std::string Tag) {
4321 std::string StructRef = "struct " + Tag;
4322 std::string S = "static void __";
4323
4324 S += funcName;
4325 S += "_block_copy_" + utostr(i);
4326 S += "(" + StructRef;
4327 S += "*dst, " + StructRef;
4328 S += "*src) {";
4329 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4330 E = ImportedBlockDecls.end(); I != E; ++I) {
4331 ValueDecl *VD = (*I);
4332 S += "_Block_object_assign((void*)&dst->";
4333 S += (*I)->getNameAsString();
4334 S += ", (void*)src->";
4335 S += (*I)->getNameAsString();
4336 if (BlockByRefDeclsPtrSet.count((*I)))
4337 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4338 else if (VD->getType()->isBlockPointerType())
4339 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4340 else
4341 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4342 }
4343 S += "}\n";
4344
4345 S += "\nstatic void __";
4346 S += funcName;
4347 S += "_block_dispose_" + utostr(i);
4348 S += "(" + StructRef;
4349 S += "*src) {";
4350 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4351 E = ImportedBlockDecls.end(); I != E; ++I) {
4352 ValueDecl *VD = (*I);
4353 S += "_Block_object_dispose((void*)src->";
4354 S += (*I)->getNameAsString();
4355 if (BlockByRefDeclsPtrSet.count((*I)))
4356 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4357 else if (VD->getType()->isBlockPointerType())
4358 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4359 else
4360 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4361 }
4362 S += "}\n";
4363 return S;
4364}
4365
4366std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4367 std::string Desc) {
4368 std::string S = "\nstruct " + Tag;
4369 std::string Constructor = " " + Tag;
4370
4371 S += " {\n struct __block_impl impl;\n";
4372 S += " struct " + Desc;
4373 S += "* Desc;\n";
4374
4375 Constructor += "(void *fp, "; // Invoke function pointer.
4376 Constructor += "struct " + Desc; // Descriptor pointer.
4377 Constructor += " *desc";
4378
4379 if (BlockDeclRefs.size()) {
4380 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004381 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004382 E = BlockByCopyDecls.end(); I != E; ++I) {
4383 S += " ";
4384 std::string FieldName = (*I)->getNameAsString();
4385 std::string ArgName = "_" + FieldName;
4386 // Handle nested closure invocation. For example:
4387 //
4388 // void (^myImportedBlock)(void);
4389 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4390 //
4391 // void (^anotherBlock)(void);
4392 // anotherBlock = ^(void) {
4393 // myImportedBlock(); // import and invoke the closure
4394 // };
4395 //
4396 if (isTopLevelBlockPointerType((*I)->getType())) {
4397 S += "struct __block_impl *";
4398 Constructor += ", void *" + ArgName;
4399 } else {
4400 QualType QT = (*I)->getType();
4401 if (HasLocalVariableExternalStorage(*I))
4402 QT = Context->getPointerType(QT);
4403 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4404 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4405 Constructor += ", " + ArgName;
4406 }
4407 S += FieldName + ";\n";
4408 }
4409 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004410 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004411 E = BlockByRefDecls.end(); I != E; ++I) {
4412 S += " ";
4413 std::string FieldName = (*I)->getNameAsString();
4414 std::string ArgName = "_" + FieldName;
4415 {
4416 std::string TypeString;
4417 RewriteByRefString(TypeString, FieldName, (*I));
4418 TypeString += " *";
4419 FieldName = TypeString + FieldName;
4420 ArgName = TypeString + ArgName;
4421 Constructor += ", " + ArgName;
4422 }
4423 S += FieldName + "; // by ref\n";
4424 }
4425 // Finish writing the constructor.
4426 Constructor += ", int flags=0)";
4427 // Initialize all "by copy" arguments.
4428 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004429 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004430 E = BlockByCopyDecls.end(); I != E; ++I) {
4431 std::string Name = (*I)->getNameAsString();
4432 if (firsTime) {
4433 Constructor += " : ";
4434 firsTime = false;
4435 }
4436 else
4437 Constructor += ", ";
4438 if (isTopLevelBlockPointerType((*I)->getType()))
4439 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4440 else
4441 Constructor += Name + "(_" + Name + ")";
4442 }
4443 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004444 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004445 E = BlockByRefDecls.end(); I != E; ++I) {
4446 std::string Name = (*I)->getNameAsString();
4447 if (firsTime) {
4448 Constructor += " : ";
4449 firsTime = false;
4450 }
4451 else
4452 Constructor += ", ";
4453 Constructor += Name + "(_" + Name + "->__forwarding)";
4454 }
4455
4456 Constructor += " {\n";
4457 if (GlobalVarDecl)
4458 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4459 else
4460 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4461 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4462
4463 Constructor += " Desc = desc;\n";
4464 } else {
4465 // Finish writing the constructor.
4466 Constructor += ", int flags=0) {\n";
4467 if (GlobalVarDecl)
4468 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4469 else
4470 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4471 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4472 Constructor += " Desc = desc;\n";
4473 }
4474 Constructor += " ";
4475 Constructor += "}\n";
4476 S += Constructor;
4477 S += "};\n";
4478 return S;
4479}
4480
4481std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4482 std::string ImplTag, int i,
4483 StringRef FunName,
4484 unsigned hasCopy) {
4485 std::string S = "\nstatic struct " + DescTag;
4486
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004487 S += " {\n size_t reserved;\n";
4488 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004489 if (hasCopy) {
4490 S += " void (*copy)(struct ";
4491 S += ImplTag; S += "*, struct ";
4492 S += ImplTag; S += "*);\n";
4493
4494 S += " void (*dispose)(struct ";
4495 S += ImplTag; S += "*);\n";
4496 }
4497 S += "} ";
4498
4499 S += DescTag + "_DATA = { 0, sizeof(struct ";
4500 S += ImplTag + ")";
4501 if (hasCopy) {
4502 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4503 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4504 }
4505 S += "};\n";
4506 return S;
4507}
4508
4509void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4510 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004511 bool RewriteSC = (GlobalVarDecl &&
4512 !Blocks.empty() &&
4513 GlobalVarDecl->getStorageClass() == SC_Static &&
4514 GlobalVarDecl->getType().getCVRQualifiers());
4515 if (RewriteSC) {
4516 std::string SC(" void __");
4517 SC += GlobalVarDecl->getNameAsString();
4518 SC += "() {}";
4519 InsertText(FunLocStart, SC);
4520 }
4521
4522 // Insert closures that were part of the function.
4523 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4524 CollectBlockDeclRefInfo(Blocks[i]);
4525 // Need to copy-in the inner copied-in variables not actually used in this
4526 // block.
4527 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004528 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004529 ValueDecl *VD = Exp->getDecl();
4530 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004531 if (!VD->hasAttr<BlocksAttr>()) {
4532 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4533 BlockByCopyDeclsPtrSet.insert(VD);
4534 BlockByCopyDecls.push_back(VD);
4535 }
4536 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004537 }
John McCall113bee02012-03-10 09:33:50 +00004538
4539 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004540 BlockByRefDeclsPtrSet.insert(VD);
4541 BlockByRefDecls.push_back(VD);
4542 }
John McCall113bee02012-03-10 09:33:50 +00004543
Fariborz Jahanian11671902012-02-07 17:11:38 +00004544 // imported objects in the inner blocks not used in the outer
4545 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004546 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004547 VD->getType()->isBlockPointerType())
4548 ImportedBlockDecls.insert(VD);
4549 }
4550
4551 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4552 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4553
4554 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4555
4556 InsertText(FunLocStart, CI);
4557
4558 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4559
4560 InsertText(FunLocStart, CF);
4561
4562 if (ImportedBlockDecls.size()) {
4563 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4564 InsertText(FunLocStart, HF);
4565 }
4566 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4567 ImportedBlockDecls.size() > 0);
4568 InsertText(FunLocStart, BD);
4569
4570 BlockDeclRefs.clear();
4571 BlockByRefDecls.clear();
4572 BlockByRefDeclsPtrSet.clear();
4573 BlockByCopyDecls.clear();
4574 BlockByCopyDeclsPtrSet.clear();
4575 ImportedBlockDecls.clear();
4576 }
4577 if (RewriteSC) {
4578 // Must insert any 'const/volatile/static here. Since it has been
4579 // removed as result of rewriting of block literals.
4580 std::string SC;
4581 if (GlobalVarDecl->getStorageClass() == SC_Static)
4582 SC = "static ";
4583 if (GlobalVarDecl->getType().isConstQualified())
4584 SC += "const ";
4585 if (GlobalVarDecl->getType().isVolatileQualified())
4586 SC += "volatile ";
4587 if (GlobalVarDecl->getType().isRestrictQualified())
4588 SC += "restrict ";
4589 InsertText(FunLocStart, SC);
4590 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004591 if (GlobalConstructionExp) {
4592 // extra fancy dance for global literal expression.
4593
4594 // Always the latest block expression on the block stack.
4595 std::string Tag = "__";
4596 Tag += FunName;
4597 Tag += "_block_impl_";
4598 Tag += utostr(Blocks.size()-1);
4599 std::string globalBuf = "static ";
4600 globalBuf += Tag; globalBuf += " ";
4601 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004602
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004603 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004604 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004605 PrintingPolicy(LangOpts));
4606 globalBuf += constructorExprBuf.str();
4607 globalBuf += ";\n";
4608 InsertText(FunLocStart, globalBuf);
4609 GlobalConstructionExp = 0;
4610 }
4611
Fariborz Jahanian11671902012-02-07 17:11:38 +00004612 Blocks.clear();
4613 InnerDeclRefsCount.clear();
4614 InnerDeclRefs.clear();
4615 RewrittenBlockExprs.clear();
4616}
4617
4618void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004619 SourceLocation FunLocStart =
4620 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4621 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004622 StringRef FuncName = FD->getName();
4623
4624 SynthesizeBlockLiterals(FunLocStart, FuncName);
4625}
4626
4627static void BuildUniqueMethodName(std::string &Name,
4628 ObjCMethodDecl *MD) {
4629 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4630 Name = IFace->getName();
4631 Name += "__" + MD->getSelector().getAsString();
4632 // Convert colons to underscores.
4633 std::string::size_type loc = 0;
4634 while ((loc = Name.find(":", loc)) != std::string::npos)
4635 Name.replace(loc, 1, "_");
4636}
4637
4638void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4639 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4640 //SourceLocation FunLocStart = MD->getLocStart();
4641 SourceLocation FunLocStart = MD->getLocStart();
4642 std::string FuncName;
4643 BuildUniqueMethodName(FuncName, MD);
4644 SynthesizeBlockLiterals(FunLocStart, FuncName);
4645}
4646
4647void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4648 for (Stmt::child_range CI = S->children(); CI; ++CI)
4649 if (*CI) {
4650 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4651 GetBlockDeclRefExprs(CBE->getBody());
4652 else
4653 GetBlockDeclRefExprs(*CI);
4654 }
4655 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004656 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4657 if (DRE->refersToEnclosingLocal()) {
4658 // FIXME: Handle enums.
4659 if (!isa<FunctionDecl>(DRE->getDecl()))
4660 BlockDeclRefs.push_back(DRE);
4661 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4662 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004663 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004664 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004665
4666 return;
4667}
4668
Craig Topper5603df42013-07-05 19:34:19 +00004669void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4670 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004671 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4672 for (Stmt::child_range CI = S->children(); CI; ++CI)
4673 if (*CI) {
4674 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4675 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4676 GetInnerBlockDeclRefExprs(CBE->getBody(),
4677 InnerBlockDeclRefs,
4678 InnerContexts);
4679 }
4680 else
4681 GetInnerBlockDeclRefExprs(*CI,
4682 InnerBlockDeclRefs,
4683 InnerContexts);
4684
4685 }
4686 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004687 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4688 if (DRE->refersToEnclosingLocal()) {
4689 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4690 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4691 InnerBlockDeclRefs.push_back(DRE);
4692 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4693 if (Var->isFunctionOrMethodVarDecl())
4694 ImportedLocalExternalDecls.insert(Var);
4695 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004696 }
4697
4698 return;
4699}
4700
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004701/// convertObjCTypeToCStyleType - This routine converts such objc types
4702/// as qualified objects, and blocks to their closest c/c++ types that
4703/// it can. It returns true if input type was modified.
4704bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4705 QualType oldT = T;
4706 convertBlockPointerToFunctionPointer(T);
4707 if (T->isFunctionPointerType()) {
4708 QualType PointeeTy;
4709 if (const PointerType* PT = T->getAs<PointerType>()) {
4710 PointeeTy = PT->getPointeeType();
4711 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4712 T = convertFunctionTypeOfBlocks(FT);
4713 T = Context->getPointerType(T);
4714 }
4715 }
4716 }
4717
4718 convertToUnqualifiedObjCType(T);
4719 return T != oldT;
4720}
4721
Fariborz Jahanian11671902012-02-07 17:11:38 +00004722/// convertFunctionTypeOfBlocks - This routine converts a function type
4723/// whose result type may be a block pointer or whose argument type(s)
4724/// might be block pointers to an equivalent function type replacing
4725/// all block pointers to function pointers.
4726QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4727 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4728 // FTP will be null for closures that don't take arguments.
4729 // Generate a funky cast.
4730 SmallVector<QualType, 8> ArgTypes;
4731 QualType Res = FT->getResultType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004732 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004733
4734 if (FTP) {
4735 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4736 E = FTP->arg_type_end(); I && (I != E); ++I) {
4737 QualType t = *I;
4738 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004739 if (convertObjCTypeToCStyleType(t))
4740 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004741 ArgTypes.push_back(t);
4742 }
4743 }
4744 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004745 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004746 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004747 else FuncType = QualType(FT, 0);
4748 return FuncType;
4749}
4750
4751Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4752 // Navigate to relevant type information.
4753 const BlockPointerType *CPT = 0;
4754
4755 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4756 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004757 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4758 CPT = MExpr->getType()->getAs<BlockPointerType>();
4759 }
4760 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4761 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4762 }
4763 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4764 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4765 else if (const ConditionalOperator *CEXPR =
4766 dyn_cast<ConditionalOperator>(BlockExp)) {
4767 Expr *LHSExp = CEXPR->getLHS();
4768 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4769 Expr *RHSExp = CEXPR->getRHS();
4770 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4771 Expr *CONDExp = CEXPR->getCond();
4772 ConditionalOperator *CondExpr =
4773 new (Context) ConditionalOperator(CONDExp,
4774 SourceLocation(), cast<Expr>(LHSStmt),
4775 SourceLocation(), cast<Expr>(RHSStmt),
4776 Exp->getType(), VK_RValue, OK_Ordinary);
4777 return CondExpr;
4778 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4779 CPT = IRE->getType()->getAs<BlockPointerType>();
4780 } else if (const PseudoObjectExpr *POE
4781 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4782 CPT = POE->getType()->castAs<BlockPointerType>();
4783 } else {
4784 assert(1 && "RewriteBlockClass: Bad type");
4785 }
4786 assert(CPT && "RewriteBlockClass: Bad type");
4787 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4788 assert(FT && "RewriteBlockClass: Bad type");
4789 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4790 // FTP will be null for closures that don't take arguments.
4791
4792 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4793 SourceLocation(), SourceLocation(),
4794 &Context->Idents.get("__block_impl"));
4795 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4796
4797 // Generate a funky cast.
4798 SmallVector<QualType, 8> ArgTypes;
4799
4800 // Push the block argument type.
4801 ArgTypes.push_back(PtrBlock);
4802 if (FTP) {
4803 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4804 E = FTP->arg_type_end(); I && (I != E); ++I) {
4805 QualType t = *I;
4806 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4807 if (!convertBlockPointerToFunctionPointer(t))
4808 convertToUnqualifiedObjCType(t);
4809 ArgTypes.push_back(t);
4810 }
4811 }
4812 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004813 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004814
4815 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4816
4817 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4818 CK_BitCast,
4819 const_cast<Expr*>(BlockExp));
4820 // Don't forget the parens to enforce the proper binding.
4821 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4822 BlkCast);
4823 //PE->dump();
4824
4825 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4826 SourceLocation(),
4827 &Context->Idents.get("FuncPtr"),
4828 Context->VoidPtrTy, 0,
4829 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004830 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004831 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4832 FD->getType(), VK_LValue,
4833 OK_Ordinary);
4834
4835
4836 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4837 CK_BitCast, ME);
4838 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4839
4840 SmallVector<Expr*, 8> BlkExprs;
4841 // Add the implicit argument.
4842 BlkExprs.push_back(BlkCast);
4843 // Add the user arguments.
4844 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4845 E = Exp->arg_end(); I != E; ++I) {
4846 BlkExprs.push_back(*I);
4847 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004848 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004849 Exp->getType(), VK_RValue,
4850 SourceLocation());
4851 return CE;
4852}
4853
4854// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004855// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004856// For example:
4857//
4858// int main() {
4859// __block Foo *f;
4860// __block int i;
4861//
4862// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004863// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004864// i = 77;
4865// };
4866//}
John McCall113bee02012-03-10 09:33:50 +00004867Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004868 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4869 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004870 ValueDecl *VD = DeclRefExp->getDecl();
4871 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004872
4873 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4874 SourceLocation(),
4875 &Context->Idents.get("__forwarding"),
4876 Context->VoidPtrTy, 0,
4877 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004878 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004879 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4880 FD, SourceLocation(),
4881 FD->getType(), VK_LValue,
4882 OK_Ordinary);
4883
4884 StringRef Name = VD->getName();
4885 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4886 &Context->Idents.get(Name),
4887 Context->VoidPtrTy, 0,
4888 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004889 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004890 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4891 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4892
4893
4894
4895 // Need parens to enforce precedence.
4896 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4897 DeclRefExp->getExprLoc(),
4898 ME);
4899 ReplaceStmt(DeclRefExp, PE);
4900 return PE;
4901}
4902
4903// Rewrites the imported local variable V with external storage
4904// (static, extern, etc.) as *V
4905//
4906Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4907 ValueDecl *VD = DRE->getDecl();
4908 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4909 if (!ImportedLocalExternalDecls.count(Var))
4910 return DRE;
4911 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4912 VK_LValue, OK_Ordinary,
4913 DRE->getLocation());
4914 // Need parens to enforce precedence.
4915 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4916 Exp);
4917 ReplaceStmt(DRE, PE);
4918 return PE;
4919}
4920
4921void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4922 SourceLocation LocStart = CE->getLParenLoc();
4923 SourceLocation LocEnd = CE->getRParenLoc();
4924
4925 // Need to avoid trying to rewrite synthesized casts.
4926 if (LocStart.isInvalid())
4927 return;
4928 // Need to avoid trying to rewrite casts contained in macros.
4929 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4930 return;
4931
4932 const char *startBuf = SM->getCharacterData(LocStart);
4933 const char *endBuf = SM->getCharacterData(LocEnd);
4934 QualType QT = CE->getType();
4935 const Type* TypePtr = QT->getAs<Type>();
4936 if (isa<TypeOfExprType>(TypePtr)) {
4937 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4938 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4939 std::string TypeAsString = "(";
4940 RewriteBlockPointerType(TypeAsString, QT);
4941 TypeAsString += ")";
4942 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4943 return;
4944 }
4945 // advance the location to startArgList.
4946 const char *argPtr = startBuf;
4947
4948 while (*argPtr++ && (argPtr < endBuf)) {
4949 switch (*argPtr) {
4950 case '^':
4951 // Replace the '^' with '*'.
4952 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4953 ReplaceText(LocStart, 1, "*");
4954 break;
4955 }
4956 }
4957 return;
4958}
4959
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004960void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4961 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004962 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4963 CastKind != CK_AnyPointerToBlockPointerCast)
4964 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004965
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004966 QualType QT = IC->getType();
4967 (void)convertBlockPointerToFunctionPointer(QT);
4968 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4969 std::string Str = "(";
4970 Str += TypeString;
4971 Str += ")";
4972 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4973
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004974 return;
4975}
4976
Fariborz Jahanian11671902012-02-07 17:11:38 +00004977void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4978 SourceLocation DeclLoc = FD->getLocation();
4979 unsigned parenCount = 0;
4980
4981 // We have 1 or more arguments that have closure pointers.
4982 const char *startBuf = SM->getCharacterData(DeclLoc);
4983 const char *startArgList = strchr(startBuf, '(');
4984
4985 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4986
4987 parenCount++;
4988 // advance the location to startArgList.
4989 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4990 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4991
4992 const char *argPtr = startArgList;
4993
4994 while (*argPtr++ && parenCount) {
4995 switch (*argPtr) {
4996 case '^':
4997 // Replace the '^' with '*'.
4998 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4999 ReplaceText(DeclLoc, 1, "*");
5000 break;
5001 case '(':
5002 parenCount++;
5003 break;
5004 case ')':
5005 parenCount--;
5006 break;
5007 }
5008 }
5009 return;
5010}
5011
5012bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5013 const FunctionProtoType *FTP;
5014 const PointerType *PT = QT->getAs<PointerType>();
5015 if (PT) {
5016 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5017 } else {
5018 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5019 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5020 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5021 }
5022 if (FTP) {
5023 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5024 E = FTP->arg_type_end(); I != E; ++I)
5025 if (isTopLevelBlockPointerType(*I))
5026 return true;
5027 }
5028 return false;
5029}
5030
5031bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5032 const FunctionProtoType *FTP;
5033 const PointerType *PT = QT->getAs<PointerType>();
5034 if (PT) {
5035 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5036 } else {
5037 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5038 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5039 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5040 }
5041 if (FTP) {
5042 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5043 E = FTP->arg_type_end(); I != E; ++I) {
5044 if ((*I)->isObjCQualifiedIdType())
5045 return true;
5046 if ((*I)->isObjCObjectPointerType() &&
5047 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5048 return true;
5049 }
5050
5051 }
5052 return false;
5053}
5054
5055void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5056 const char *&RParen) {
5057 const char *argPtr = strchr(Name, '(');
5058 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5059
5060 LParen = argPtr; // output the start.
5061 argPtr++; // skip past the left paren.
5062 unsigned parenCount = 1;
5063
5064 while (*argPtr && parenCount) {
5065 switch (*argPtr) {
5066 case '(': parenCount++; break;
5067 case ')': parenCount--; break;
5068 default: break;
5069 }
5070 if (parenCount) argPtr++;
5071 }
5072 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5073 RParen = argPtr; // output the end
5074}
5075
5076void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5078 RewriteBlockPointerFunctionArgs(FD);
5079 return;
5080 }
5081 // Handle Variables and Typedefs.
5082 SourceLocation DeclLoc = ND->getLocation();
5083 QualType DeclT;
5084 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5085 DeclT = VD->getType();
5086 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5087 DeclT = TDD->getUnderlyingType();
5088 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5089 DeclT = FD->getType();
5090 else
5091 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5092
5093 const char *startBuf = SM->getCharacterData(DeclLoc);
5094 const char *endBuf = startBuf;
5095 // scan backward (from the decl location) for the end of the previous decl.
5096 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5097 startBuf--;
5098 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5099 std::string buf;
5100 unsigned OrigLength=0;
5101 // *startBuf != '^' if we are dealing with a pointer to function that
5102 // may take block argument types (which will be handled below).
5103 if (*startBuf == '^') {
5104 // Replace the '^' with '*', computing a negative offset.
5105 buf = '*';
5106 startBuf++;
5107 OrigLength++;
5108 }
5109 while (*startBuf != ')') {
5110 buf += *startBuf;
5111 startBuf++;
5112 OrigLength++;
5113 }
5114 buf += ')';
5115 OrigLength++;
5116
5117 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5118 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5119 // Replace the '^' with '*' for arguments.
5120 // Replace id<P> with id/*<>*/
5121 DeclLoc = ND->getLocation();
5122 startBuf = SM->getCharacterData(DeclLoc);
5123 const char *argListBegin, *argListEnd;
5124 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5125 while (argListBegin < argListEnd) {
5126 if (*argListBegin == '^')
5127 buf += '*';
5128 else if (*argListBegin == '<') {
5129 buf += "/*";
5130 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005131 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005132 while (*argListBegin != '>') {
5133 buf += *argListBegin++;
5134 OrigLength++;
5135 }
5136 buf += *argListBegin;
5137 buf += "*/";
5138 }
5139 else
5140 buf += *argListBegin;
5141 argListBegin++;
5142 OrigLength++;
5143 }
5144 buf += ')';
5145 OrigLength++;
5146 }
5147 ReplaceText(Start, OrigLength, buf);
5148
5149 return;
5150}
5151
5152
5153/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5154/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5155/// struct Block_byref_id_object *src) {
5156/// _Block_object_assign (&_dest->object, _src->object,
5157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5158/// [|BLOCK_FIELD_IS_WEAK]) // object
5159/// _Block_object_assign(&_dest->object, _src->object,
5160/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5161/// [|BLOCK_FIELD_IS_WEAK]) // block
5162/// }
5163/// And:
5164/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5165/// _Block_object_dispose(_src->object,
5166/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5167/// [|BLOCK_FIELD_IS_WEAK]) // object
5168/// _Block_object_dispose(_src->object,
5169/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5170/// [|BLOCK_FIELD_IS_WEAK]) // block
5171/// }
5172
5173std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5174 int flag) {
5175 std::string S;
5176 if (CopyDestroyCache.count(flag))
5177 return S;
5178 CopyDestroyCache.insert(flag);
5179 S = "static void __Block_byref_id_object_copy_";
5180 S += utostr(flag);
5181 S += "(void *dst, void *src) {\n";
5182
5183 // offset into the object pointer is computed as:
5184 // void * + void* + int + int + void* + void *
5185 unsigned IntSize =
5186 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5187 unsigned VoidPtrSize =
5188 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5189
5190 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5191 S += " _Block_object_assign((char*)dst + ";
5192 S += utostr(offset);
5193 S += ", *(void * *) ((char*)src + ";
5194 S += utostr(offset);
5195 S += "), ";
5196 S += utostr(flag);
5197 S += ");\n}\n";
5198
5199 S += "static void __Block_byref_id_object_dispose_";
5200 S += utostr(flag);
5201 S += "(void *src) {\n";
5202 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5203 S += utostr(offset);
5204 S += "), ";
5205 S += utostr(flag);
5206 S += ");\n}\n";
5207 return S;
5208}
5209
5210/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5211/// the declaration into:
5212/// struct __Block_byref_ND {
5213/// void *__isa; // NULL for everything except __weak pointers
5214/// struct __Block_byref_ND *__forwarding;
5215/// int32_t __flags;
5216/// int32_t __size;
5217/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5218/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5219/// typex ND;
5220/// };
5221///
5222/// It then replaces declaration of ND variable with:
5223/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5224/// __size=sizeof(struct __Block_byref_ND),
5225/// ND=initializer-if-any};
5226///
5227///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005228void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5229 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005230 int flag = 0;
5231 int isa = 0;
5232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5233 if (DeclLoc.isInvalid())
5234 // If type location is missing, it is because of missing type (a warning).
5235 // Use variable's location which is good for this case.
5236 DeclLoc = ND->getLocation();
5237 const char *startBuf = SM->getCharacterData(DeclLoc);
5238 SourceLocation X = ND->getLocEnd();
5239 X = SM->getExpansionLoc(X);
5240 const char *endBuf = SM->getCharacterData(X);
5241 std::string Name(ND->getNameAsString());
5242 std::string ByrefType;
5243 RewriteByRefString(ByrefType, Name, ND, true);
5244 ByrefType += " {\n";
5245 ByrefType += " void *__isa;\n";
5246 RewriteByRefString(ByrefType, Name, ND);
5247 ByrefType += " *__forwarding;\n";
5248 ByrefType += " int __flags;\n";
5249 ByrefType += " int __size;\n";
5250 // Add void *__Block_byref_id_object_copy;
5251 // void *__Block_byref_id_object_dispose; if needed.
5252 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005253 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005254 if (HasCopyAndDispose) {
5255 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5256 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5257 }
5258
5259 QualType T = Ty;
5260 (void)convertBlockPointerToFunctionPointer(T);
5261 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5262
5263 ByrefType += " " + Name + ";\n";
5264 ByrefType += "};\n";
5265 // Insert this type in global scope. It is needed by helper function.
5266 SourceLocation FunLocStart;
5267 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005268 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005269 else {
5270 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5271 FunLocStart = CurMethodDef->getLocStart();
5272 }
5273 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005274
Fariborz Jahanian11671902012-02-07 17:11:38 +00005275 if (Ty.isObjCGCWeak()) {
5276 flag |= BLOCK_FIELD_IS_WEAK;
5277 isa = 1;
5278 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005279 if (HasCopyAndDispose) {
5280 flag = BLOCK_BYREF_CALLER;
5281 QualType Ty = ND->getType();
5282 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5283 if (Ty->isBlockPointerType())
5284 flag |= BLOCK_FIELD_IS_BLOCK;
5285 else
5286 flag |= BLOCK_FIELD_IS_OBJECT;
5287 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5288 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005289 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005290 }
5291
5292 // struct __Block_byref_ND ND =
5293 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5294 // initializer-if-any};
5295 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005296 // FIXME. rewriter does not support __block c++ objects which
5297 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005298 if (hasInit)
5299 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5300 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5301 if (CXXDecl && CXXDecl->isDefaultConstructor())
5302 hasInit = false;
5303 }
5304
Fariborz Jahanian11671902012-02-07 17:11:38 +00005305 unsigned flags = 0;
5306 if (HasCopyAndDispose)
5307 flags |= BLOCK_HAS_COPY_DISPOSE;
5308 Name = ND->getNameAsString();
5309 ByrefType.clear();
5310 RewriteByRefString(ByrefType, Name, ND);
5311 std::string ForwardingCastType("(");
5312 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005313 ByrefType += " " + Name + " = {(void*)";
5314 ByrefType += utostr(isa);
5315 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5316 ByrefType += utostr(flags);
5317 ByrefType += ", ";
5318 ByrefType += "sizeof(";
5319 RewriteByRefString(ByrefType, Name, ND);
5320 ByrefType += ")";
5321 if (HasCopyAndDispose) {
5322 ByrefType += ", __Block_byref_id_object_copy_";
5323 ByrefType += utostr(flag);
5324 ByrefType += ", __Block_byref_id_object_dispose_";
5325 ByrefType += utostr(flag);
5326 }
5327
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005328 if (!firstDecl) {
5329 // In multiple __block declarations, and for all but 1st declaration,
5330 // find location of the separating comma. This would be start location
5331 // where new text is to be inserted.
5332 DeclLoc = ND->getLocation();
5333 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5334 const char *commaBuf = startDeclBuf;
5335 while (*commaBuf != ',')
5336 commaBuf--;
5337 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5338 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5339 startBuf = commaBuf;
5340 }
5341
Fariborz Jahanian11671902012-02-07 17:11:38 +00005342 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005343 ByrefType += "};\n";
5344 unsigned nameSize = Name.size();
5345 // for block or function pointer declaration. Name is aleady
5346 // part of the declaration.
5347 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5348 nameSize = 1;
5349 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5350 }
5351 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005352 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005353 SourceLocation startLoc;
5354 Expr *E = ND->getInit();
5355 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5356 startLoc = ECE->getLParenLoc();
5357 else
5358 startLoc = E->getLocStart();
5359 startLoc = SM->getExpansionLoc(startLoc);
5360 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005361 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005362
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005363 const char separator = lastDecl ? ';' : ',';
5364 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5365 const char *separatorBuf = strchr(startInitializerBuf, separator);
5366 assert((*separatorBuf == separator) &&
5367 "RewriteByRefVar: can't find ';' or ','");
5368 SourceLocation separatorLoc =
5369 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5370
5371 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005372 }
5373 return;
5374}
5375
5376void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5377 // Add initializers for any closure decl refs.
5378 GetBlockDeclRefExprs(Exp->getBody());
5379 if (BlockDeclRefs.size()) {
5380 // Unique all "by copy" declarations.
5381 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005382 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005383 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5384 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5385 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5386 }
5387 }
5388 // Unique all "by ref" declarations.
5389 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005390 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005391 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5392 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5393 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5394 }
5395 }
5396 // Find any imported blocks...they will need special attention.
5397 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005398 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005399 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5400 BlockDeclRefs[i]->getType()->isBlockPointerType())
5401 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5402 }
5403}
5404
5405FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5406 IdentifierInfo *ID = &Context->Idents.get(name);
5407 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5408 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5409 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005410 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005411}
5412
5413Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005414 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005415
Fariborz Jahanian11671902012-02-07 17:11:38 +00005416 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005417
Fariborz Jahanian11671902012-02-07 17:11:38 +00005418 Blocks.push_back(Exp);
5419
5420 CollectBlockDeclRefInfo(Exp);
5421
5422 // Add inner imported variables now used in current block.
5423 int countOfInnerDecls = 0;
5424 if (!InnerBlockDeclRefs.empty()) {
5425 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005426 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005427 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005428 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005429 // We need to save the copied-in variables in nested
5430 // blocks because it is needed at the end for some of the API generations.
5431 // See SynthesizeBlockLiterals routine.
5432 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5433 BlockDeclRefs.push_back(Exp);
5434 BlockByCopyDeclsPtrSet.insert(VD);
5435 BlockByCopyDecls.push_back(VD);
5436 }
John McCall113bee02012-03-10 09:33:50 +00005437 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005438 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5439 BlockDeclRefs.push_back(Exp);
5440 BlockByRefDeclsPtrSet.insert(VD);
5441 BlockByRefDecls.push_back(VD);
5442 }
5443 }
5444 // Find any imported blocks...they will need special attention.
5445 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005446 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005447 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5448 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5449 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5450 }
5451 InnerDeclRefsCount.push_back(countOfInnerDecls);
5452
5453 std::string FuncName;
5454
5455 if (CurFunctionDef)
5456 FuncName = CurFunctionDef->getNameAsString();
5457 else if (CurMethodDef)
5458 BuildUniqueMethodName(FuncName, CurMethodDef);
5459 else if (GlobalVarDecl)
5460 FuncName = std::string(GlobalVarDecl->getNameAsString());
5461
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005462 bool GlobalBlockExpr =
5463 block->getDeclContext()->getRedeclContext()->isFileContext();
5464
5465 if (GlobalBlockExpr && !GlobalVarDecl) {
5466 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5467 GlobalBlockExpr = false;
5468 }
5469
Fariborz Jahanian11671902012-02-07 17:11:38 +00005470 std::string BlockNumber = utostr(Blocks.size()-1);
5471
Fariborz Jahanian11671902012-02-07 17:11:38 +00005472 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5473
5474 // Get a pointer to the function type so we can cast appropriately.
5475 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5476 QualType FType = Context->getPointerType(BFT);
5477
5478 FunctionDecl *FD;
5479 Expr *NewRep;
5480
Benjamin Kramer60509af2013-09-09 14:48:42 +00005481 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005482 std::string Tag;
5483
5484 if (GlobalBlockExpr)
5485 Tag = "__global_";
5486 else
5487 Tag = "__";
5488 Tag += FuncName + "_block_impl_" + BlockNumber;
5489
Fariborz Jahanian11671902012-02-07 17:11:38 +00005490 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005491 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005492 SourceLocation());
5493
5494 SmallVector<Expr*, 4> InitExprs;
5495
5496 // Initialize the block function.
5497 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005498 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5499 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005500 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5501 CK_BitCast, Arg);
5502 InitExprs.push_back(castExpr);
5503
5504 // Initialize the block descriptor.
5505 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5506
5507 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5508 SourceLocation(), SourceLocation(),
5509 &Context->Idents.get(DescData.c_str()),
5510 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005511 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005512 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005513 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005514 Context->VoidPtrTy,
5515 VK_LValue,
5516 SourceLocation()),
5517 UO_AddrOf,
5518 Context->getPointerType(Context->VoidPtrTy),
5519 VK_RValue, OK_Ordinary,
5520 SourceLocation());
5521 InitExprs.push_back(DescRefExpr);
5522
5523 // Add initializers for any closure decl refs.
5524 if (BlockDeclRefs.size()) {
5525 Expr *Exp;
5526 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005527 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005528 E = BlockByCopyDecls.end(); I != E; ++I) {
5529 if (isObjCType((*I)->getType())) {
5530 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5531 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005532 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5533 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005534 if (HasLocalVariableExternalStorage(*I)) {
5535 QualType QT = (*I)->getType();
5536 QT = Context->getPointerType(QT);
5537 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5538 OK_Ordinary, SourceLocation());
5539 }
5540 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5541 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005542 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5543 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005544 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5545 CK_BitCast, Arg);
5546 } else {
5547 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005548 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5549 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005550 if (HasLocalVariableExternalStorage(*I)) {
5551 QualType QT = (*I)->getType();
5552 QT = Context->getPointerType(QT);
5553 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5554 OK_Ordinary, SourceLocation());
5555 }
5556
5557 }
5558 InitExprs.push_back(Exp);
5559 }
5560 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005561 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005562 E = BlockByRefDecls.end(); I != E; ++I) {
5563 ValueDecl *ND = (*I);
5564 std::string Name(ND->getNameAsString());
5565 std::string RecName;
5566 RewriteByRefString(RecName, Name, ND, true);
5567 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5568 + sizeof("struct"));
5569 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5570 SourceLocation(), SourceLocation(),
5571 II);
5572 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5573 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5574
5575 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005576 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005577 SourceLocation());
5578 bool isNestedCapturedVar = false;
5579 if (block)
5580 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5581 ce = block->capture_end(); ci != ce; ++ci) {
5582 const VarDecl *variable = ci->getVariable();
5583 if (variable == ND && ci->isNested()) {
5584 assert (ci->isByRef() &&
5585 "SynthBlockInitExpr - captured block variable is not byref");
5586 isNestedCapturedVar = true;
5587 break;
5588 }
5589 }
5590 // captured nested byref variable has its address passed. Do not take
5591 // its address again.
5592 if (!isNestedCapturedVar)
5593 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5594 Context->getPointerType(Exp->getType()),
5595 VK_RValue, OK_Ordinary, SourceLocation());
5596 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5597 InitExprs.push_back(Exp);
5598 }
5599 }
5600 if (ImportedBlockDecls.size()) {
5601 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5602 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5603 unsigned IntSize =
5604 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5605 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5606 Context->IntTy, SourceLocation());
5607 InitExprs.push_back(FlagExp);
5608 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005609 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005610 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005611
5612 if (GlobalBlockExpr) {
5613 assert (GlobalConstructionExp == 0 &&
5614 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5615 GlobalConstructionExp = NewRep;
5616 NewRep = DRE;
5617 }
5618
Fariborz Jahanian11671902012-02-07 17:11:38 +00005619 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5620 Context->getPointerType(NewRep->getType()),
5621 VK_RValue, OK_Ordinary, SourceLocation());
5622 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5623 NewRep);
5624 BlockDeclRefs.clear();
5625 BlockByRefDecls.clear();
5626 BlockByRefDeclsPtrSet.clear();
5627 BlockByCopyDecls.clear();
5628 BlockByCopyDeclsPtrSet.clear();
5629 ImportedBlockDecls.clear();
5630 return NewRep;
5631}
5632
5633bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5634 if (const ObjCForCollectionStmt * CS =
5635 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5636 return CS->getElement() == DS;
5637 return false;
5638}
5639
5640//===----------------------------------------------------------------------===//
5641// Function Body / Expression rewriting
5642//===----------------------------------------------------------------------===//
5643
5644Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5645 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5646 isa<DoStmt>(S) || isa<ForStmt>(S))
5647 Stmts.push_back(S);
5648 else if (isa<ObjCForCollectionStmt>(S)) {
5649 Stmts.push_back(S);
5650 ObjCBcLabelNo.push_back(++BcLabelCount);
5651 }
5652
5653 // Pseudo-object operations and ivar references need special
5654 // treatment because we're going to recursively rewrite them.
5655 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5656 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5657 return RewritePropertyOrImplicitSetter(PseudoOp);
5658 } else {
5659 return RewritePropertyOrImplicitGetter(PseudoOp);
5660 }
5661 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5662 return RewriteObjCIvarRefExpr(IvarRefExpr);
5663 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005664 else if (isa<OpaqueValueExpr>(S))
5665 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005666
5667 SourceRange OrigStmtRange = S->getSourceRange();
5668
5669 // Perform a bottom up rewrite of all children.
5670 for (Stmt::child_range CI = S->children(); CI; ++CI)
5671 if (*CI) {
5672 Stmt *childStmt = (*CI);
5673 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5674 if (newStmt) {
5675 *CI = newStmt;
5676 }
5677 }
5678
5679 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005680 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005681 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5682 InnerContexts.insert(BE->getBlockDecl());
5683 ImportedLocalExternalDecls.clear();
5684 GetInnerBlockDeclRefExprs(BE->getBody(),
5685 InnerBlockDeclRefs, InnerContexts);
5686 // Rewrite the block body in place.
5687 Stmt *SaveCurrentBody = CurrentBody;
5688 CurrentBody = BE->getBody();
5689 PropParentMap = 0;
5690 // block literal on rhs of a property-dot-sytax assignment
5691 // must be replaced by its synthesize ast so getRewrittenText
5692 // works as expected. In this case, what actually ends up on RHS
5693 // is the blockTranscribed which is the helper function for the
5694 // block literal; as in: self.c = ^() {[ace ARR];};
5695 bool saveDisableReplaceStmt = DisableReplaceStmt;
5696 DisableReplaceStmt = false;
5697 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5698 DisableReplaceStmt = saveDisableReplaceStmt;
5699 CurrentBody = SaveCurrentBody;
5700 PropParentMap = 0;
5701 ImportedLocalExternalDecls.clear();
5702 // Now we snarf the rewritten text and stash it away for later use.
5703 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5704 RewrittenBlockExprs[BE] = Str;
5705
5706 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5707
5708 //blockTranscribed->dump();
5709 ReplaceStmt(S, blockTranscribed);
5710 return blockTranscribed;
5711 }
5712 // Handle specific things.
5713 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5714 return RewriteAtEncode(AtEncode);
5715
5716 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5717 return RewriteAtSelector(AtSelector);
5718
5719 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5720 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005721
5722 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5723 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005724
Patrick Beard0caa3942012-04-19 00:25:12 +00005725 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5726 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005727
5728 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5729 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005730
5731 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5732 dyn_cast<ObjCDictionaryLiteral>(S))
5733 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005734
5735 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5736#if 0
5737 // Before we rewrite it, put the original message expression in a comment.
5738 SourceLocation startLoc = MessExpr->getLocStart();
5739 SourceLocation endLoc = MessExpr->getLocEnd();
5740
5741 const char *startBuf = SM->getCharacterData(startLoc);
5742 const char *endBuf = SM->getCharacterData(endLoc);
5743
5744 std::string messString;
5745 messString += "// ";
5746 messString.append(startBuf, endBuf-startBuf+1);
5747 messString += "\n";
5748
5749 // FIXME: Missing definition of
5750 // InsertText(clang::SourceLocation, char const*, unsigned int).
5751 // InsertText(startLoc, messString.c_str(), messString.size());
5752 // Tried this, but it didn't work either...
5753 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5754#endif
5755 return RewriteMessageExpr(MessExpr);
5756 }
5757
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005758 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5759 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5760 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5761 }
5762
Fariborz Jahanian11671902012-02-07 17:11:38 +00005763 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5764 return RewriteObjCTryStmt(StmtTry);
5765
5766 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5767 return RewriteObjCSynchronizedStmt(StmtTry);
5768
5769 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5770 return RewriteObjCThrowStmt(StmtThrow);
5771
5772 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5773 return RewriteObjCProtocolExpr(ProtocolExp);
5774
5775 if (ObjCForCollectionStmt *StmtForCollection =
5776 dyn_cast<ObjCForCollectionStmt>(S))
5777 return RewriteObjCForCollectionStmt(StmtForCollection,
5778 OrigStmtRange.getEnd());
5779 if (BreakStmt *StmtBreakStmt =
5780 dyn_cast<BreakStmt>(S))
5781 return RewriteBreakStmt(StmtBreakStmt);
5782 if (ContinueStmt *StmtContinueStmt =
5783 dyn_cast<ContinueStmt>(S))
5784 return RewriteContinueStmt(StmtContinueStmt);
5785
5786 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5787 // and cast exprs.
5788 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5789 // FIXME: What we're doing here is modifying the type-specifier that
5790 // precedes the first Decl. In the future the DeclGroup should have
5791 // a separate type-specifier that we can rewrite.
5792 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5793 // the context of an ObjCForCollectionStmt. For example:
5794 // NSArray *someArray;
5795 // for (id <FooProtocol> index in someArray) ;
5796 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5797 // and it depends on the original text locations/positions.
5798 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5799 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5800
5801 // Blocks rewrite rules.
5802 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5803 DI != DE; ++DI) {
5804 Decl *SD = *DI;
5805 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5806 if (isTopLevelBlockPointerType(ND->getType()))
5807 RewriteBlockPointerDecl(ND);
5808 else if (ND->getType()->isFunctionPointerType())
5809 CheckFunctionPointerDecl(ND->getType(), ND);
5810 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5811 if (VD->hasAttr<BlocksAttr>()) {
5812 static unsigned uniqueByrefDeclCount = 0;
5813 assert(!BlockByRefDeclNo.count(ND) &&
5814 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5815 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005816 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005817 }
5818 else
5819 RewriteTypeOfDecl(VD);
5820 }
5821 }
5822 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5823 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5824 RewriteBlockPointerDecl(TD);
5825 else if (TD->getUnderlyingType()->isFunctionPointerType())
5826 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5827 }
5828 }
5829 }
5830
5831 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5832 RewriteObjCQualifiedInterfaceTypes(CE);
5833
5834 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5835 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5836 assert(!Stmts.empty() && "Statement stack is empty");
5837 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5838 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5839 && "Statement stack mismatch");
5840 Stmts.pop_back();
5841 }
5842 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005843 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5844 ValueDecl *VD = DRE->getDecl();
5845 if (VD->hasAttr<BlocksAttr>())
5846 return RewriteBlockDeclRefExpr(DRE);
5847 if (HasLocalVariableExternalStorage(VD))
5848 return RewriteLocalVariableExternalStorage(DRE);
5849 }
5850
5851 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5852 if (CE->getCallee()->getType()->isBlockPointerType()) {
5853 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5854 ReplaceStmt(S, BlockCall);
5855 return BlockCall;
5856 }
5857 }
5858 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5859 RewriteCastExpr(CE);
5860 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005861 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5862 RewriteImplicitCastObjCExpr(ICE);
5863 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005864#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005865
Fariborz Jahanian11671902012-02-07 17:11:38 +00005866 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5867 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5868 ICE->getSubExpr(),
5869 SourceLocation());
5870 // Get the new text.
5871 std::string SStr;
5872 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005873 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005874 const std::string &Str = Buf.str();
5875
5876 printf("CAST = %s\n", &Str[0]);
5877 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5878 delete S;
5879 return Replacement;
5880 }
5881#endif
5882 // Return this stmt unmodified.
5883 return S;
5884}
5885
5886void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5887 for (RecordDecl::field_iterator i = RD->field_begin(),
5888 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005889 FieldDecl *FD = *i;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005890 if (isTopLevelBlockPointerType(FD->getType()))
5891 RewriteBlockPointerDecl(FD);
5892 if (FD->getType()->isObjCQualifiedIdType() ||
5893 FD->getType()->isObjCQualifiedInterfaceType())
5894 RewriteObjCQualifiedInterfaceTypes(FD);
5895 }
5896}
5897
5898/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5899/// main file of the input.
5900void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5901 switch (D->getKind()) {
5902 case Decl::Function: {
5903 FunctionDecl *FD = cast<FunctionDecl>(D);
5904 if (FD->isOverloadedOperator())
5905 return;
5906
5907 // Since function prototypes don't have ParmDecl's, we check the function
5908 // prototype. This enables us to rewrite function declarations and
5909 // definitions using the same code.
5910 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5911
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005912 if (!FD->isThisDeclarationADefinition())
5913 break;
5914
Fariborz Jahanian11671902012-02-07 17:11:38 +00005915 // FIXME: If this should support Obj-C++, support CXXTryStmt
5916 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5917 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005918 CurrentBody = Body;
5919 Body =
5920 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5921 FD->setBody(Body);
5922 CurrentBody = 0;
5923 if (PropParentMap) {
5924 delete PropParentMap;
5925 PropParentMap = 0;
5926 }
5927 // This synthesizes and inserts the block "impl" struct, invoke function,
5928 // and any copy/dispose helper functions.
5929 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005930 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005931 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005932 }
5933 break;
5934 }
5935 case Decl::ObjCMethod: {
5936 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5937 if (CompoundStmt *Body = MD->getCompoundBody()) {
5938 CurMethodDef = MD;
5939 CurrentBody = Body;
5940 Body =
5941 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5942 MD->setBody(Body);
5943 CurrentBody = 0;
5944 if (PropParentMap) {
5945 delete PropParentMap;
5946 PropParentMap = 0;
5947 }
5948 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005949 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005950 CurMethodDef = 0;
5951 }
5952 break;
5953 }
5954 case Decl::ObjCImplementation: {
5955 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5956 ClassImplementation.push_back(CI);
5957 break;
5958 }
5959 case Decl::ObjCCategoryImpl: {
5960 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5961 CategoryImplementation.push_back(CI);
5962 break;
5963 }
5964 case Decl::Var: {
5965 VarDecl *VD = cast<VarDecl>(D);
5966 RewriteObjCQualifiedInterfaceTypes(VD);
5967 if (isTopLevelBlockPointerType(VD->getType()))
5968 RewriteBlockPointerDecl(VD);
5969 else if (VD->getType()->isFunctionPointerType()) {
5970 CheckFunctionPointerDecl(VD->getType(), VD);
5971 if (VD->getInit()) {
5972 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5973 RewriteCastExpr(CE);
5974 }
5975 }
5976 } else if (VD->getType()->isRecordType()) {
5977 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5978 if (RD->isCompleteDefinition())
5979 RewriteRecordBody(RD);
5980 }
5981 if (VD->getInit()) {
5982 GlobalVarDecl = VD;
5983 CurrentBody = VD->getInit();
5984 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5985 CurrentBody = 0;
5986 if (PropParentMap) {
5987 delete PropParentMap;
5988 PropParentMap = 0;
5989 }
5990 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5991 GlobalVarDecl = 0;
5992
5993 // This is needed for blocks.
5994 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5995 RewriteCastExpr(CE);
5996 }
5997 }
5998 break;
5999 }
6000 case Decl::TypeAlias:
6001 case Decl::Typedef: {
6002 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6003 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
6004 RewriteBlockPointerDecl(TD);
6005 else if (TD->getUnderlyingType()->isFunctionPointerType())
6006 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00006007 else
6008 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006009 }
6010 break;
6011 }
6012 case Decl::CXXRecord:
6013 case Decl::Record: {
6014 RecordDecl *RD = cast<RecordDecl>(D);
6015 if (RD->isCompleteDefinition())
6016 RewriteRecordBody(RD);
6017 break;
6018 }
6019 default:
6020 break;
6021 }
6022 // Nothing yet.
6023}
6024
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006025/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6026/// protocol reference symbols in the for of:
6027/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6028static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6029 ObjCProtocolDecl *PDecl,
6030 std::string &Result) {
6031 // Also output .objc_protorefs$B section and its meta-data.
6032 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00006033 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006034 Result += "struct _protocol_t *";
6035 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6036 Result += PDecl->getNameAsString();
6037 Result += " = &";
6038 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6039 Result += ";\n";
6040}
6041
Fariborz Jahanian11671902012-02-07 17:11:38 +00006042void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6043 if (Diags.hasErrorOccurred())
6044 return;
6045
6046 RewriteInclude();
6047
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006048 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6049 // translation of function bodies were postponed untill all class and
6050 // their extensions and implementations are seen. This is because, we
6051 // cannot build grouping structs for bitfields untill they are all seen.
6052 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6053 HandleTopLevelSingleDecl(FDecl);
6054 }
6055
Fariborz Jahanian11671902012-02-07 17:11:38 +00006056 // Here's a great place to add any extra declarations that may be needed.
6057 // Write out meta data for each @protocol(<expr>).
6058 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006059 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006060 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006061 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6062 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006063
6064 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006065
6066 if (ClassImplementation.size() || CategoryImplementation.size())
6067 RewriteImplementations();
6068
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006069 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6070 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6071 // Write struct declaration for the class matching its ivar declarations.
6072 // Note that for modern abi, this is postponed until the end of TU
6073 // because class extensions and the implementation might declare their own
6074 // private ivars.
6075 RewriteInterfaceDecl(CDecl);
6076 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006077
Fariborz Jahanian11671902012-02-07 17:11:38 +00006078 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6079 // we are done.
6080 if (const RewriteBuffer *RewriteBuf =
6081 Rewrite.getRewriteBufferFor(MainFileID)) {
6082 //printf("Changed:\n");
6083 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6084 } else {
6085 llvm::errs() << "No changes\n";
6086 }
6087
6088 if (ClassImplementation.size() || CategoryImplementation.size() ||
6089 ProtocolExprDecls.size()) {
6090 // Rewrite Objective-c meta data*
6091 std::string ResultStr;
6092 RewriteMetaDataIntoBuffer(ResultStr);
6093 // Emit metadata.
6094 *OutFile << ResultStr;
6095 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006096 // Emit ImageInfo;
6097 {
6098 std::string ResultStr;
6099 WriteImageInfo(ResultStr);
6100 *OutFile << ResultStr;
6101 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006102 OutFile->flush();
6103}
6104
6105void RewriteModernObjC::Initialize(ASTContext &context) {
6106 InitializeCommon(context);
6107
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006108 Preamble += "#ifndef __OBJC2__\n";
6109 Preamble += "#define __OBJC2__\n";
6110 Preamble += "#endif\n";
6111
Fariborz Jahanian11671902012-02-07 17:11:38 +00006112 // declaring objc_selector outside the parameter list removes a silly
6113 // scope related warning...
6114 if (IsHeader)
6115 Preamble = "#pragma once\n";
6116 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006117 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6118 Preamble += "\n\tstruct objc_object *superClass; ";
6119 // Add a constructor for creating temporary objects.
6120 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6121 Preamble += ": object(o), superClass(s) {} ";
6122 Preamble += "\n};\n";
6123
Fariborz Jahanian11671902012-02-07 17:11:38 +00006124 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006125 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006126 // These are currently generated.
6127 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006128 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006129 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006130 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6131 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006132 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006133 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006134 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6135 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006136 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006137
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006138 // These need be generated for performance. Currently they are not,
6139 // using API calls instead.
6140 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6141 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6142 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6143
Fariborz Jahanian11671902012-02-07 17:11:38 +00006144 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006145 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6146 Preamble += "typedef struct objc_object Protocol;\n";
6147 Preamble += "#define _REWRITER_typedef_Protocol\n";
6148 Preamble += "#endif\n";
6149 if (LangOpts.MicrosoftExt) {
6150 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6151 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006152 }
6153 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006154 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006155
6156 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6157 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6158 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6159 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6160 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6161
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006162 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006163 Preamble += "(const char *);\n";
6164 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6165 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006166 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006167 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006168 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006169 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006170 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6171 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006172 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006173 Preamble += "#ifdef _WIN64\n";
6174 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6175 Preamble += "#else\n";
6176 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6177 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006178 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6179 Preamble += "struct __objcFastEnumerationState {\n\t";
6180 Preamble += "unsigned long state;\n\t";
6181 Preamble += "void **itemsPtr;\n\t";
6182 Preamble += "unsigned long *mutationsPtr;\n\t";
6183 Preamble += "unsigned long extra[5];\n};\n";
6184 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6185 Preamble += "#define __FASTENUMERATIONSTATE\n";
6186 Preamble += "#endif\n";
6187 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6188 Preamble += "struct __NSConstantStringImpl {\n";
6189 Preamble += " int *isa;\n";
6190 Preamble += " int flags;\n";
6191 Preamble += " char *str;\n";
6192 Preamble += " long length;\n";
6193 Preamble += "};\n";
6194 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6195 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6196 Preamble += "#else\n";
6197 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6198 Preamble += "#endif\n";
6199 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6200 Preamble += "#endif\n";
6201 // Blocks preamble.
6202 Preamble += "#ifndef BLOCK_IMPL\n";
6203 Preamble += "#define BLOCK_IMPL\n";
6204 Preamble += "struct __block_impl {\n";
6205 Preamble += " void *isa;\n";
6206 Preamble += " int Flags;\n";
6207 Preamble += " int Reserved;\n";
6208 Preamble += " void *FuncPtr;\n";
6209 Preamble += "};\n";
6210 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6211 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6212 Preamble += "extern \"C\" __declspec(dllexport) "
6213 "void _Block_object_assign(void *, const void *, const int);\n";
6214 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6215 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6216 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6217 Preamble += "#else\n";
6218 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6219 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6220 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6221 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6222 Preamble += "#endif\n";
6223 Preamble += "#endif\n";
6224 if (LangOpts.MicrosoftExt) {
6225 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6226 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6227 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6228 Preamble += "#define __attribute__(X)\n";
6229 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006230 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006231 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006232 Preamble += "#endif\n";
6233 Preamble += "#ifndef __block\n";
6234 Preamble += "#define __block\n";
6235 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006236 }
6237 else {
6238 Preamble += "#define __block\n";
6239 Preamble += "#define __weak\n";
6240 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006241
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006242 // Declarations required for modern objective-c array and dictionary literals.
6243 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006244 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006245 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006246 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006247 Preamble += "\tva_list marker;\n";
6248 Preamble += "\tva_start(marker, count);\n";
6249 Preamble += "\tarr = new void *[count];\n";
6250 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6251 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6252 Preamble += "\tva_end( marker );\n";
6253 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006254 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006255 Preamble += "\tdelete[] arr;\n";
6256 Preamble += " }\n";
6257 Preamble += "};\n";
6258
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006259 // Declaration required for implementation of @autoreleasepool statement.
6260 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6261 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6262 Preamble += "struct __AtAutoreleasePool {\n";
6263 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6264 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6265 Preamble += " void * atautoreleasepoolobj;\n";
6266 Preamble += "};\n";
6267
Fariborz Jahanian11671902012-02-07 17:11:38 +00006268 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6269 // as this avoids warning in any 64bit/32bit compilation model.
6270 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6271}
6272
6273/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6274/// ivar offset.
6275void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6276 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006277 Result += "__OFFSETOFIVAR__(struct ";
6278 Result += ivar->getContainingInterface()->getNameAsString();
6279 if (LangOpts.MicrosoftExt)
6280 Result += "_IMPL";
6281 Result += ", ";
6282 if (ivar->isBitField())
6283 ObjCIvarBitfieldGroupDecl(ivar, Result);
6284 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006285 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006286 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006287}
6288
6289/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6290/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006291/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006292/// char *attributes;
6293/// }
6294
6295/// struct _prop_list_t {
6296/// uint32_t entsize; // sizeof(struct _prop_t)
6297/// uint32_t count_of_properties;
6298/// struct _prop_t prop_list[count_of_properties];
6299/// }
6300
6301/// struct _protocol_t;
6302
6303/// struct _protocol_list_t {
6304/// long protocol_count; // Note, this is 32/64 bit
6305/// struct _protocol_t * protocol_list[protocol_count];
6306/// }
6307
6308/// struct _objc_method {
6309/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006310/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006311/// char *_imp;
6312/// }
6313
6314/// struct _method_list_t {
6315/// uint32_t entsize; // sizeof(struct _objc_method)
6316/// uint32_t method_count;
6317/// struct _objc_method method_list[method_count];
6318/// }
6319
6320/// struct _protocol_t {
6321/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006322/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006323/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006324/// const struct method_list_t *instance_methods;
6325/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006326/// const struct method_list_t *optionalInstanceMethods;
6327/// const struct method_list_t *optionalClassMethods;
6328/// const struct _prop_list_t * properties;
6329/// const uint32_t size; // sizeof(struct _protocol_t)
6330/// const uint32_t flags; // = 0
6331/// const char ** extendedMethodTypes;
6332/// }
6333
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006334/// struct _ivar_t {
6335/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006336/// const char *name;
6337/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006338/// uint32_t alignment;
6339/// uint32_t size;
6340/// }
6341
6342/// struct _ivar_list_t {
6343/// uint32 entsize; // sizeof(struct _ivar_t)
6344/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006345/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006346/// }
6347
6348/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006349/// uint32_t flags;
6350/// uint32_t instanceStart;
6351/// uint32_t instanceSize;
6352/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006353/// const uint8_t *ivarLayout;
6354/// const char *name;
6355/// const struct _method_list_t *baseMethods;
6356/// const struct _protocol_list_t *baseProtocols;
6357/// const struct _ivar_list_t *ivars;
6358/// const uint8_t *weakIvarLayout;
6359/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006360/// }
6361
6362/// struct _class_t {
6363/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006364/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006365/// void *cache;
6366/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006367/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006368/// }
6369
6370/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006371/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006372/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006373/// const struct _method_list_t *instance_methods;
6374/// const struct _method_list_t *class_methods;
6375/// const struct _protocol_list_t *protocols;
6376/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006377/// }
6378
6379/// MessageRefTy - LLVM for:
6380/// struct _message_ref_t {
6381/// IMP messenger;
6382/// SEL name;
6383/// };
6384
6385/// SuperMessageRefTy - LLVM for:
6386/// struct _super_message_ref_t {
6387/// SUPER_IMP messenger;
6388/// SEL name;
6389/// };
6390
Fariborz Jahanian45489622012-03-14 18:09:23 +00006391static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006392 static bool meta_data_declared = false;
6393 if (meta_data_declared)
6394 return;
6395
6396 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006397 Result += "\tconst char *name;\n";
6398 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006399 Result += "};\n";
6400
6401 Result += "\nstruct _protocol_t;\n";
6402
Fariborz Jahanian11671902012-02-07 17:11:38 +00006403 Result += "\nstruct _objc_method {\n";
6404 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006405 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006406 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006407 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006408
6409 Result += "\nstruct _protocol_t {\n";
6410 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006411 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006412 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006413 Result += "\tconst struct method_list_t *instance_methods;\n";
6414 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006415 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6416 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6417 Result += "\tconst struct _prop_list_t * properties;\n";
6418 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6419 Result += "\tconst unsigned int flags; // = 0\n";
6420 Result += "\tconst char ** extendedMethodTypes;\n";
6421 Result += "};\n";
6422
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006423 Result += "\nstruct _ivar_t {\n";
6424 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006425 Result += "\tconst char *name;\n";
6426 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006427 Result += "\tunsigned int alignment;\n";
6428 Result += "\tunsigned int size;\n";
6429 Result += "};\n";
6430
6431 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006432 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006433 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006434 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006435 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6436 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006437 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006438 Result += "\tconst unsigned char *ivarLayout;\n";
6439 Result += "\tconst char *name;\n";
6440 Result += "\tconst struct _method_list_t *baseMethods;\n";
6441 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6442 Result += "\tconst struct _ivar_list_t *ivars;\n";
6443 Result += "\tconst unsigned char *weakIvarLayout;\n";
6444 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006445 Result += "};\n";
6446
6447 Result += "\nstruct _class_t {\n";
6448 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006449 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006450 Result += "\tvoid *cache;\n";
6451 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006452 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006453 Result += "};\n";
6454
6455 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006456 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006457 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006458 Result += "\tconst struct _method_list_t *instance_methods;\n";
6459 Result += "\tconst struct _method_list_t *class_methods;\n";
6460 Result += "\tconst struct _protocol_list_t *protocols;\n";
6461 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006462 Result += "};\n";
6463
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006464 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006465 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006466 meta_data_declared = true;
6467}
6468
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006469static void Write_protocol_list_t_TypeDecl(std::string &Result,
6470 long super_protocol_count) {
6471 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6472 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6473 Result += "\tstruct _protocol_t *super_protocols[";
6474 Result += utostr(super_protocol_count); Result += "];\n";
6475 Result += "}";
6476}
6477
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006478static void Write_method_list_t_TypeDecl(std::string &Result,
6479 unsigned int method_count) {
6480 Result += "struct /*_method_list_t*/"; Result += " {\n";
6481 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6482 Result += "\tunsigned int method_count;\n";
6483 Result += "\tstruct _objc_method method_list[";
6484 Result += utostr(method_count); Result += "];\n";
6485 Result += "}";
6486}
6487
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006488static void Write__prop_list_t_TypeDecl(std::string &Result,
6489 unsigned int property_count) {
6490 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6491 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6492 Result += "\tunsigned int count_of_properties;\n";
6493 Result += "\tstruct _prop_t prop_list[";
6494 Result += utostr(property_count); Result += "];\n";
6495 Result += "}";
6496}
6497
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006498static void Write__ivar_list_t_TypeDecl(std::string &Result,
6499 unsigned int ivar_count) {
6500 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6501 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6502 Result += "\tunsigned int count;\n";
6503 Result += "\tstruct _ivar_t ivar_list[";
6504 Result += utostr(ivar_count); Result += "];\n";
6505 Result += "}";
6506}
6507
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006508static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6509 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6510 StringRef VarName,
6511 StringRef ProtocolName) {
6512 if (SuperProtocols.size() > 0) {
6513 Result += "\nstatic ";
6514 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6515 Result += " "; Result += VarName;
6516 Result += ProtocolName;
6517 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6518 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6519 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6520 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6521 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6522 Result += SuperPD->getNameAsString();
6523 if (i == e-1)
6524 Result += "\n};\n";
6525 else
6526 Result += ",\n";
6527 }
6528 }
6529}
6530
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006531static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6532 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006533 ArrayRef<ObjCMethodDecl *> Methods,
6534 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006535 StringRef TopLevelDeclName,
6536 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006537 if (Methods.size() > 0) {
6538 Result += "\nstatic ";
6539 Write_method_list_t_TypeDecl(Result, Methods.size());
6540 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006541 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006542 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6543 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6544 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6545 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6546 ObjCMethodDecl *MD = Methods[i];
6547 if (i == 0)
6548 Result += "\t{{(struct objc_selector *)\"";
6549 else
6550 Result += "\t{(struct objc_selector *)\"";
6551 Result += (MD)->getSelector().getAsString(); Result += "\"";
6552 Result += ", ";
6553 std::string MethodTypeString;
6554 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6555 Result += "\""; Result += MethodTypeString; Result += "\"";
6556 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006557 if (!MethodImpl)
6558 Result += "0";
6559 else {
6560 Result += "(void *)";
6561 Result += RewriteObj.MethodInternalNames[MD];
6562 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006563 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006564 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006565 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006566 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006567 }
6568 Result += "};\n";
6569 }
6570}
6571
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006572static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006573 ASTContext *Context, std::string &Result,
6574 ArrayRef<ObjCPropertyDecl *> Properties,
6575 const Decl *Container,
6576 StringRef VarName,
6577 StringRef ProtocolName) {
6578 if (Properties.size() > 0) {
6579 Result += "\nstatic ";
6580 Write__prop_list_t_TypeDecl(Result, Properties.size());
6581 Result += " "; Result += VarName;
6582 Result += ProtocolName;
6583 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6584 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6585 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6586 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6587 ObjCPropertyDecl *PropDecl = Properties[i];
6588 if (i == 0)
6589 Result += "\t{{\"";
6590 else
6591 Result += "\t{\"";
6592 Result += PropDecl->getName(); Result += "\",";
6593 std::string PropertyTypeString, QuotePropertyTypeString;
6594 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6595 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6596 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6597 if (i == e-1)
6598 Result += "}}\n";
6599 else
6600 Result += "},\n";
6601 }
6602 Result += "};\n";
6603 }
6604}
6605
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006606// Metadata flags
6607enum MetaDataDlags {
6608 CLS = 0x0,
6609 CLS_META = 0x1,
6610 CLS_ROOT = 0x2,
6611 OBJC2_CLS_HIDDEN = 0x10,
6612 CLS_EXCEPTION = 0x20,
6613
6614 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6615 CLS_HAS_IVAR_RELEASER = 0x40,
6616 /// class was compiled with -fobjc-arr
6617 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6618};
6619
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006620static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6621 unsigned int flags,
6622 const std::string &InstanceStart,
6623 const std::string &InstanceSize,
6624 ArrayRef<ObjCMethodDecl *>baseMethods,
6625 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6626 ArrayRef<ObjCIvarDecl *>ivars,
6627 ArrayRef<ObjCPropertyDecl *>Properties,
6628 StringRef VarName,
6629 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006630 Result += "\nstatic struct _class_ro_t ";
6631 Result += VarName; Result += ClassName;
6632 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6633 Result += "\t";
6634 Result += llvm::utostr(flags); Result += ", ";
6635 Result += InstanceStart; Result += ", ";
6636 Result += InstanceSize; Result += ", \n";
6637 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006638 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6639 if (Triple.getArch() == llvm::Triple::x86_64)
6640 // uint32_t const reserved; // only when building for 64bit targets
6641 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006642 // const uint8_t * const ivarLayout;
6643 Result += "0, \n\t";
6644 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006645 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006646 if (baseMethods.size() > 0) {
6647 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006648 if (metaclass)
6649 Result += "_OBJC_$_CLASS_METHODS_";
6650 else
6651 Result += "_OBJC_$_INSTANCE_METHODS_";
6652 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006653 Result += ",\n\t";
6654 }
6655 else
6656 Result += "0, \n\t";
6657
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006658 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006659 Result += "(const struct _objc_protocol_list *)&";
6660 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6661 Result += ",\n\t";
6662 }
6663 else
6664 Result += "0, \n\t";
6665
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006666 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006667 Result += "(const struct _ivar_list_t *)&";
6668 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6669 Result += ",\n\t";
6670 }
6671 else
6672 Result += "0, \n\t";
6673
6674 // weakIvarLayout
6675 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006676 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006677 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006678 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006679 Result += ",\n";
6680 }
6681 else
6682 Result += "0, \n";
6683
6684 Result += "};\n";
6685}
6686
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006687static void Write_class_t(ASTContext *Context, std::string &Result,
6688 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006689 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6690 bool rootClass = (!CDecl->getSuperClass());
6691 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006692
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006693 if (!rootClass) {
6694 // Find the Root class
6695 RootClass = CDecl->getSuperClass();
6696 while (RootClass->getSuperClass()) {
6697 RootClass = RootClass->getSuperClass();
6698 }
6699 }
6700
6701 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006702 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006703 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006704 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006705 if (CDecl->getImplementation())
6706 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006707 else
6708 Result += "__declspec(dllimport) ";
6709
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006710 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006711 Result += CDecl->getNameAsString();
6712 Result += ";\n";
6713 }
6714 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006715 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006716 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006717 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006718 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006719 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006720 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006721 else
6722 Result += "__declspec(dllimport) ";
6723
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006724 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006725 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006726 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006727 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006728
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006729 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006730 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006731 if (RootClass->getImplementation())
6732 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006733 else
6734 Result += "__declspec(dllimport) ";
6735
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006736 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006737 Result += VarName;
6738 Result += RootClass->getNameAsString();
6739 Result += ";\n";
6740 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006741 }
6742
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006743 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6744 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006745 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6746 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006747 if (metaclass) {
6748 if (!rootClass) {
6749 Result += "0, // &"; Result += VarName;
6750 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006751 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006752 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006753 Result += CDecl->getSuperClass()->getNameAsString();
6754 Result += ",\n\t";
6755 }
6756 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006757 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006758 Result += CDecl->getNameAsString();
6759 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006760 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006761 Result += ",\n\t";
6762 }
6763 }
6764 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006765 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006766 Result += CDecl->getNameAsString();
6767 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006768 if (!rootClass) {
6769 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006770 Result += CDecl->getSuperClass()->getNameAsString();
6771 Result += ",\n\t";
6772 }
6773 else
6774 Result += "0,\n\t";
6775 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006776 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6777 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6778 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006779 Result += "&_OBJC_METACLASS_RO_$_";
6780 else
6781 Result += "&_OBJC_CLASS_RO_$_";
6782 Result += CDecl->getNameAsString();
6783 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006784
6785 // Add static function to initialize some of the meta-data fields.
6786 // avoid doing it twice.
6787 if (metaclass)
6788 return;
6789
6790 const ObjCInterfaceDecl *SuperClass =
6791 rootClass ? CDecl : CDecl->getSuperClass();
6792
6793 Result += "static void OBJC_CLASS_SETUP_$_";
6794 Result += CDecl->getNameAsString();
6795 Result += "(void ) {\n";
6796 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6797 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006798 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006799
6800 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006801 Result += ".superclass = ";
6802 if (rootClass)
6803 Result += "&OBJC_CLASS_$_";
6804 else
6805 Result += "&OBJC_METACLASS_$_";
6806
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006807 Result += SuperClass->getNameAsString(); Result += ";\n";
6808
6809 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6810 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6811
6812 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6813 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6814 Result += CDecl->getNameAsString(); Result += ";\n";
6815
6816 if (!rootClass) {
6817 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6818 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6819 Result += SuperClass->getNameAsString(); Result += ";\n";
6820 }
6821
6822 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6823 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6824 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006825}
6826
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006827static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6828 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006829 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006830 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006831 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6832 ArrayRef<ObjCMethodDecl *> ClassMethods,
6833 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6834 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006835 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006836 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006837 // must declare an extern class object in case this class is not implemented
6838 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006839 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006840 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006841 if (ClassDecl->getImplementation())
6842 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006843 else
6844 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006845
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006846 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006847 Result += "OBJC_CLASS_$_"; Result += ClassName;
6848 Result += ";\n";
6849
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006850 Result += "\nstatic struct _category_t ";
6851 Result += "_OBJC_$_CATEGORY_";
6852 Result += ClassName; Result += "_$_"; Result += CatName;
6853 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6854 Result += "{\n";
6855 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006856 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006857 Result += ",\n";
6858 if (InstanceMethods.size() > 0) {
6859 Result += "\t(const struct _method_list_t *)&";
6860 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6861 Result += ClassName; Result += "_$_"; Result += CatName;
6862 Result += ",\n";
6863 }
6864 else
6865 Result += "\t0,\n";
6866
6867 if (ClassMethods.size() > 0) {
6868 Result += "\t(const struct _method_list_t *)&";
6869 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6870 Result += ClassName; Result += "_$_"; Result += CatName;
6871 Result += ",\n";
6872 }
6873 else
6874 Result += "\t0,\n";
6875
6876 if (RefedProtocols.size() > 0) {
6877 Result += "\t(const struct _protocol_list_t *)&";
6878 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6879 Result += ClassName; Result += "_$_"; Result += CatName;
6880 Result += ",\n";
6881 }
6882 else
6883 Result += "\t0,\n";
6884
6885 if (ClassProperties.size() > 0) {
6886 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6887 Result += ClassName; Result += "_$_"; Result += CatName;
6888 Result += ",\n";
6889 }
6890 else
6891 Result += "\t0,\n";
6892
6893 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006894
6895 // Add static function to initialize the class pointer in the category structure.
6896 Result += "static void OBJC_CATEGORY_SETUP_$_";
6897 Result += ClassDecl->getNameAsString();
6898 Result += "_$_";
6899 Result += CatName;
6900 Result += "(void ) {\n";
6901 Result += "\t_OBJC_$_CATEGORY_";
6902 Result += ClassDecl->getNameAsString();
6903 Result += "_$_";
6904 Result += CatName;
6905 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6906 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006907}
6908
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006909static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6910 ASTContext *Context, std::string &Result,
6911 ArrayRef<ObjCMethodDecl *> Methods,
6912 StringRef VarName,
6913 StringRef ProtocolName) {
6914 if (Methods.size() == 0)
6915 return;
6916
6917 Result += "\nstatic const char *";
6918 Result += VarName; Result += ProtocolName;
6919 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6920 Result += "{\n";
6921 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6922 ObjCMethodDecl *MD = Methods[i];
6923 std::string MethodTypeString, QuoteMethodTypeString;
6924 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6925 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6926 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6927 if (i == e-1)
6928 Result += "\n};\n";
6929 else {
6930 Result += ",\n";
6931 }
6932 }
6933}
6934
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006935static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6936 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006937 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006938 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006939 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006940 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6941 // this is what happens:
6942 /**
6943 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6944 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6945 Class->getVisibility() == HiddenVisibility)
6946 Visibility shoud be: HiddenVisibility;
6947 else
6948 Visibility shoud be: DefaultVisibility;
6949 */
6950
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006951 Result += "\n";
6952 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6953 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006954 if (Context->getLangOpts().MicrosoftExt)
6955 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6956
6957 if (!Context->getLangOpts().MicrosoftExt ||
6958 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006959 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006960 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006961 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006962 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006963 if (Ivars[i]->isBitField())
6964 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6965 else
6966 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006967 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6968 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006969 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6970 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006971 if (Ivars[i]->isBitField()) {
6972 // skip over rest of the ivar bitfields.
6973 SKIP_BITFIELDS(i , e, Ivars);
6974 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006975 }
6976}
6977
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006978static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6979 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006980 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006981 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006982 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006983 if (OriginalIvars.size() > 0) {
6984 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6985 SmallVector<ObjCIvarDecl *, 8> Ivars;
6986 // strip off all but the first ivar bitfield from each group of ivars.
6987 // Such ivars in the ivar list table will be replaced by their grouping struct
6988 // 'ivar'.
6989 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6990 if (OriginalIvars[i]->isBitField()) {
6991 Ivars.push_back(OriginalIvars[i]);
6992 // skip over rest of the ivar bitfields.
6993 SKIP_BITFIELDS(i , e, OriginalIvars);
6994 }
6995 else
6996 Ivars.push_back(OriginalIvars[i]);
6997 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006998
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006999 Result += "\nstatic ";
7000 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
7001 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007002 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007003 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
7004 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
7005 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
7006 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
7007 ObjCIvarDecl *IvarDecl = Ivars[i];
7008 if (i == 0)
7009 Result += "\t{{";
7010 else
7011 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007012 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007013 if (Ivars[i]->isBitField())
7014 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7015 else
7016 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00007017 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007018
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007019 Result += "\"";
7020 if (Ivars[i]->isBitField())
7021 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7022 else
7023 Result += IvarDecl->getName();
7024 Result += "\", ";
7025
7026 QualType IVQT = IvarDecl->getType();
7027 if (IvarDecl->isBitField())
7028 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7029
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007030 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007031 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007032 IvarDecl);
7033 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7034 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7035
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007036 // FIXME. this alignment represents the host alignment and need be changed to
7037 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007038 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007039 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007040 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007041 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00007042 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007043 if (i == e-1)
7044 Result += "}}\n";
7045 else
7046 Result += "},\n";
7047 }
7048 Result += "};\n";
7049 }
7050}
7051
Fariborz Jahanian11671902012-02-07 17:11:38 +00007052/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007053void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7054 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007055
Fariborz Jahanian11671902012-02-07 17:11:38 +00007056 // Do not synthesize the protocol more than once.
7057 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7058 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007059 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007060
7061 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7062 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007063 // Must write out all protocol definitions in current qualifier list,
7064 // and in their nested qualifiers before writing out current definition.
7065 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7066 E = PDecl->protocol_end(); I != E; ++I)
7067 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007068
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007069 // Construct method lists.
7070 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7071 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7072 for (ObjCProtocolDecl::instmeth_iterator
7073 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7074 I != E; ++I) {
7075 ObjCMethodDecl *MD = *I;
7076 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7077 OptInstanceMethods.push_back(MD);
7078 } else {
7079 InstanceMethods.push_back(MD);
7080 }
7081 }
7082
7083 for (ObjCProtocolDecl::classmeth_iterator
7084 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7085 I != E; ++I) {
7086 ObjCMethodDecl *MD = *I;
7087 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7088 OptClassMethods.push_back(MD);
7089 } else {
7090 ClassMethods.push_back(MD);
7091 }
7092 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007093 std::vector<ObjCMethodDecl *> AllMethods;
7094 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7095 AllMethods.push_back(InstanceMethods[i]);
7096 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7097 AllMethods.push_back(ClassMethods[i]);
7098 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7099 AllMethods.push_back(OptInstanceMethods[i]);
7100 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7101 AllMethods.push_back(OptClassMethods[i]);
7102
7103 Write__extendedMethodTypes_initializer(*this, Context, Result,
7104 AllMethods,
7105 "_OBJC_PROTOCOL_METHOD_TYPES_",
7106 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007107 // Protocol's super protocol list
7108 std::vector<ObjCProtocolDecl *> SuperProtocols;
7109 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7110 E = PDecl->protocol_end(); I != E; ++I)
7111 SuperProtocols.push_back(*I);
7112
7113 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7114 "_OBJC_PROTOCOL_REFS_",
7115 PDecl->getNameAsString());
7116
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007117 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007118 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007119 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007120
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007121 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007122 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007123 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007124
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007125 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007126 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007127 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007128
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007129 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007130 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007131 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007132
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007133 // Protocol's property metadata.
7134 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7135 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7136 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007137 ProtocolProperties.push_back(*I);
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007138
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007139 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007140 /* Container */0,
7141 "_OBJC_PROTOCOL_PROPERTIES_",
7142 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007143
Fariborz Jahanian48985802012-02-08 00:50:52 +00007144 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007145 Result += "\n";
7146 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007147 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007148 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007149 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007150 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7151 Result += "\t0,\n"; // id is; is null
7152 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007153 if (SuperProtocols.size() > 0) {
7154 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7155 Result += PDecl->getNameAsString(); Result += ",\n";
7156 }
7157 else
7158 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007159 if (InstanceMethods.size() > 0) {
7160 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7161 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007162 }
7163 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007164 Result += "\t0,\n";
7165
7166 if (ClassMethods.size() > 0) {
7167 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7168 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007169 }
7170 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007171 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007172
Fariborz Jahanian48985802012-02-08 00:50:52 +00007173 if (OptInstanceMethods.size() > 0) {
7174 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7175 Result += PDecl->getNameAsString(); Result += ",\n";
7176 }
7177 else
7178 Result += "\t0,\n";
7179
7180 if (OptClassMethods.size() > 0) {
7181 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7182 Result += PDecl->getNameAsString(); Result += ",\n";
7183 }
7184 else
7185 Result += "\t0,\n";
7186
7187 if (ProtocolProperties.size() > 0) {
7188 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7189 Result += PDecl->getNameAsString(); Result += ",\n";
7190 }
7191 else
7192 Result += "\t0,\n";
7193
7194 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7195 Result += "\t0,\n";
7196
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007197 if (AllMethods.size() > 0) {
7198 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7199 Result += PDecl->getNameAsString();
7200 Result += "\n};\n";
7201 }
7202 else
7203 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007204
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007205 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007206 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007207 Result += "struct _protocol_t *";
7208 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7209 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7210 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007211
Fariborz Jahanian11671902012-02-07 17:11:38 +00007212 // Mark this protocol as having been generated.
7213 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7214 llvm_unreachable("protocol already synthesized");
7215
7216}
7217
7218void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7219 const ObjCList<ObjCProtocolDecl> &Protocols,
7220 StringRef prefix, StringRef ClassName,
7221 std::string &Result) {
7222 if (Protocols.empty()) return;
7223
7224 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007225 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007226
7227 // Output the top lovel protocol meta-data for the class.
7228 /* struct _objc_protocol_list {
7229 struct _objc_protocol_list *next;
7230 int protocol_count;
7231 struct _objc_protocol *class_protocols[];
7232 }
7233 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007234 Result += "\n";
7235 if (LangOpts.MicrosoftExt)
7236 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7237 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007238 Result += "\tstruct _objc_protocol_list *next;\n";
7239 Result += "\tint protocol_count;\n";
7240 Result += "\tstruct _objc_protocol *class_protocols[";
7241 Result += utostr(Protocols.size());
7242 Result += "];\n} _OBJC_";
7243 Result += prefix;
7244 Result += "_PROTOCOLS_";
7245 Result += ClassName;
7246 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7247 "{\n\t0, ";
7248 Result += utostr(Protocols.size());
7249 Result += "\n";
7250
7251 Result += "\t,{&_OBJC_PROTOCOL_";
7252 Result += Protocols[0]->getNameAsString();
7253 Result += " \n";
7254
7255 for (unsigned i = 1; i != Protocols.size(); i++) {
7256 Result += "\t ,&_OBJC_PROTOCOL_";
7257 Result += Protocols[i]->getNameAsString();
7258 Result += "\n";
7259 }
7260 Result += "\t }\n};\n";
7261}
7262
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007263/// hasObjCExceptionAttribute - Return true if this class or any super
7264/// class has the __objc_exception__ attribute.
7265/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7266static bool hasObjCExceptionAttribute(ASTContext &Context,
7267 const ObjCInterfaceDecl *OID) {
7268 if (OID->hasAttr<ObjCExceptionAttr>())
7269 return true;
7270 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7271 return hasObjCExceptionAttribute(Context, Super);
7272 return false;
7273}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007274
Fariborz Jahanian11671902012-02-07 17:11:38 +00007275void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7276 std::string &Result) {
7277 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7278
7279 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007280 if (CDecl->isImplicitInterfaceDecl())
7281 assert(false &&
7282 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007283
Fariborz Jahanian45489622012-03-14 18:09:23 +00007284 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007285 SmallVector<ObjCIvarDecl *, 8> IVars;
7286
7287 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7288 IVD; IVD = IVD->getNextIvar()) {
7289 // Ignore unnamed bit-fields.
7290 if (!IVD->getDeclName())
7291 continue;
7292 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007293 }
7294
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007295 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007296 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007297 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007298
7299 // Build _objc_method_list for class's instance methods if needed
7300 SmallVector<ObjCMethodDecl *, 32>
7301 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7302
7303 // If any of our property implementations have associated getters or
7304 // setters, produce metadata for them as well.
7305 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7306 PropEnd = IDecl->propimpl_end();
7307 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007308 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007309 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007310 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007311 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007312 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007313 if (!PD)
7314 continue;
7315 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007316 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007317 InstanceMethods.push_back(Getter);
7318 if (PD->isReadOnly())
7319 continue;
7320 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007321 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007322 InstanceMethods.push_back(Setter);
7323 }
7324
7325 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7326 "_OBJC_$_INSTANCE_METHODS_",
7327 IDecl->getNameAsString(), true);
7328
7329 SmallVector<ObjCMethodDecl *, 32>
7330 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7331
7332 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7333 "_OBJC_$_CLASS_METHODS_",
7334 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007335
7336 // Protocols referenced in class declaration?
7337 // Protocol's super protocol list
7338 std::vector<ObjCProtocolDecl *> RefedProtocols;
7339 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7340 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7341 E = Protocols.end();
7342 I != E; ++I) {
7343 RefedProtocols.push_back(*I);
7344 // Must write out all protocol definitions in current qualifier list,
7345 // and in their nested qualifiers before writing out current definition.
7346 RewriteObjCProtocolMetaData(*I, Result);
7347 }
7348
7349 Write_protocol_list_initializer(Context, Result,
7350 RefedProtocols,
7351 "_OBJC_CLASS_PROTOCOLS_$_",
7352 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007353
7354 // Protocol's property metadata.
7355 std::vector<ObjCPropertyDecl *> ClassProperties;
7356 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7357 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007358 ClassProperties.push_back(*I);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007359
7360 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007361 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007362 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007363 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007364
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007365
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007366 // Data for initializing _class_ro_t metaclass meta-data
7367 uint32_t flags = CLS_META;
7368 std::string InstanceSize;
7369 std::string InstanceStart;
7370
7371
7372 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7373 if (classIsHidden)
7374 flags |= OBJC2_CLS_HIDDEN;
7375
7376 if (!CDecl->getSuperClass())
7377 // class is root
7378 flags |= CLS_ROOT;
7379 InstanceSize = "sizeof(struct _class_t)";
7380 InstanceStart = InstanceSize;
7381 Write__class_ro_t_initializer(Context, Result, flags,
7382 InstanceStart, InstanceSize,
7383 ClassMethods,
7384 0,
7385 0,
7386 0,
7387 "_OBJC_METACLASS_RO_$_",
7388 CDecl->getNameAsString());
7389
7390
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007391 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007392 flags = CLS;
7393 if (classIsHidden)
7394 flags |= OBJC2_CLS_HIDDEN;
7395
7396 if (hasObjCExceptionAttribute(*Context, CDecl))
7397 flags |= CLS_EXCEPTION;
7398
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007399 if (!CDecl->getSuperClass())
7400 // class is root
7401 flags |= CLS_ROOT;
7402
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007403 InstanceSize.clear();
7404 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007405 if (!ObjCSynthesizedStructs.count(CDecl)) {
7406 InstanceSize = "0";
7407 InstanceStart = "0";
7408 }
7409 else {
7410 InstanceSize = "sizeof(struct ";
7411 InstanceSize += CDecl->getNameAsString();
7412 InstanceSize += "_IMPL)";
7413
7414 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7415 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007416 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007417 }
7418 else
7419 InstanceStart = InstanceSize;
7420 }
7421 Write__class_ro_t_initializer(Context, Result, flags,
7422 InstanceStart, InstanceSize,
7423 InstanceMethods,
7424 RefedProtocols,
7425 IVars,
7426 ClassProperties,
7427 "_OBJC_CLASS_RO_$_",
7428 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007429
7430 Write_class_t(Context, Result,
7431 "OBJC_METACLASS_$_",
7432 CDecl, /*metaclass*/true);
7433
7434 Write_class_t(Context, Result,
7435 "OBJC_CLASS_$_",
7436 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007437
7438 if (ImplementationIsNonLazy(IDecl))
7439 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007440
Fariborz Jahanian11671902012-02-07 17:11:38 +00007441}
7442
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007443void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7444 int ClsDefCount = ClassImplementation.size();
7445 if (!ClsDefCount)
7446 return;
7447 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7448 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7449 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7450 for (int i = 0; i < ClsDefCount; i++) {
7451 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7452 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7453 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7454 Result += CDecl->getName(); Result += ",\n";
7455 }
7456 Result += "};\n";
7457}
7458
Fariborz Jahanian11671902012-02-07 17:11:38 +00007459void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7460 int ClsDefCount = ClassImplementation.size();
7461 int CatDefCount = CategoryImplementation.size();
7462
7463 // For each implemented class, write out all its meta data.
7464 for (int i = 0; i < ClsDefCount; i++)
7465 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7466
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007467 RewriteClassSetupInitHook(Result);
7468
Fariborz Jahanian11671902012-02-07 17:11:38 +00007469 // For each implemented category, write out all its meta data.
7470 for (int i = 0; i < CatDefCount; i++)
7471 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7472
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007473 RewriteCategorySetupInitHook(Result);
7474
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007475 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007476 if (LangOpts.MicrosoftExt)
7477 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007478 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7479 Result += llvm::utostr(ClsDefCount); Result += "]";
7480 Result +=
7481 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7482 "regular,no_dead_strip\")))= {\n";
7483 for (int i = 0; i < ClsDefCount; i++) {
7484 Result += "\t&OBJC_CLASS_$_";
7485 Result += ClassImplementation[i]->getNameAsString();
7486 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007487 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007488 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007489
7490 if (!DefinedNonLazyClasses.empty()) {
7491 if (LangOpts.MicrosoftExt)
7492 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7493 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7494 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7495 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7496 Result += ",\n";
7497 }
7498 Result += "};\n";
7499 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007500 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007501
7502 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007503 if (LangOpts.MicrosoftExt)
7504 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007505 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7506 Result += llvm::utostr(CatDefCount); Result += "]";
7507 Result +=
7508 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7509 "regular,no_dead_strip\")))= {\n";
7510 for (int i = 0; i < CatDefCount; i++) {
7511 Result += "\t&_OBJC_$_CATEGORY_";
7512 Result +=
7513 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7514 Result += "_$_";
7515 Result += CategoryImplementation[i]->getNameAsString();
7516 Result += ",\n";
7517 }
7518 Result += "};\n";
7519 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007520
7521 if (!DefinedNonLazyCategories.empty()) {
7522 if (LangOpts.MicrosoftExt)
7523 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7524 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7525 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7526 Result += "\t&_OBJC_$_CATEGORY_";
7527 Result +=
7528 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7529 Result += "_$_";
7530 Result += DefinedNonLazyCategories[i]->getNameAsString();
7531 Result += ",\n";
7532 }
7533 Result += "};\n";
7534 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007535}
7536
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007537void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7538 if (LangOpts.MicrosoftExt)
7539 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7540
7541 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7542 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007543 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007544}
7545
Fariborz Jahanian11671902012-02-07 17:11:38 +00007546/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7547/// implementation.
7548void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7549 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007550 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007551 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7552 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007553 ObjCCategoryDecl *CDecl
7554 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007555
7556 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007557 FullCategoryName += "_$_";
7558 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007559
7560 // Build _objc_method_list for class's instance methods if needed
7561 SmallVector<ObjCMethodDecl *, 32>
7562 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7563
7564 // If any of our property implementations have associated getters or
7565 // setters, produce metadata for them as well.
7566 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7567 PropEnd = IDecl->propimpl_end();
7568 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007569 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007570 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007571 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007572 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007573 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007574 if (!PD)
7575 continue;
7576 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7577 InstanceMethods.push_back(Getter);
7578 if (PD->isReadOnly())
7579 continue;
7580 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7581 InstanceMethods.push_back(Setter);
7582 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007583
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007584 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7585 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7586 FullCategoryName, true);
7587
7588 SmallVector<ObjCMethodDecl *, 32>
7589 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7590
7591 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7592 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7593 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007594
7595 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007596 // Protocol's super protocol list
7597 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007598 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7599 E = CDecl->protocol_end();
7600
7601 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007602 RefedProtocols.push_back(*I);
7603 // Must write out all protocol definitions in current qualifier list,
7604 // and in their nested qualifiers before writing out current definition.
7605 RewriteObjCProtocolMetaData(*I, Result);
7606 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007607
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007608 Write_protocol_list_initializer(Context, Result,
7609 RefedProtocols,
7610 "_OBJC_CATEGORY_PROTOCOLS_$_",
7611 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007612
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007613 // Protocol's property metadata.
7614 std::vector<ObjCPropertyDecl *> ClassProperties;
7615 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7616 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007617 ClassProperties.push_back(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007618
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007619 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007620 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007621 "_OBJC_$_PROP_LIST_",
7622 FullCategoryName);
7623
7624 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007625 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007626 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007627 InstanceMethods,
7628 ClassMethods,
7629 RefedProtocols,
7630 ClassProperties);
7631
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007632 // Determine if this category is also "non-lazy".
7633 if (ImplementationIsNonLazy(IDecl))
7634 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007635
7636}
7637
7638void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7639 int CatDefCount = CategoryImplementation.size();
7640 if (!CatDefCount)
7641 return;
7642 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7643 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7644 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7645 for (int i = 0; i < CatDefCount; i++) {
7646 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7647 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7648 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7649 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7650 Result += ClassDecl->getName();
7651 Result += "_$_";
7652 Result += CatDecl->getName();
7653 Result += ",\n";
7654 }
7655 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007656}
7657
7658// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7659/// class methods.
7660template<typename MethodIterator>
7661void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7662 MethodIterator MethodEnd,
7663 bool IsInstanceMethod,
7664 StringRef prefix,
7665 StringRef ClassName,
7666 std::string &Result) {
7667 if (MethodBegin == MethodEnd) return;
7668
7669 if (!objc_impl_method) {
7670 /* struct _objc_method {
7671 SEL _cmd;
7672 char *method_types;
7673 void *_imp;
7674 }
7675 */
7676 Result += "\nstruct _objc_method {\n";
7677 Result += "\tSEL _cmd;\n";
7678 Result += "\tchar *method_types;\n";
7679 Result += "\tvoid *_imp;\n";
7680 Result += "};\n";
7681
7682 objc_impl_method = true;
7683 }
7684
7685 // Build _objc_method_list for class's methods if needed
7686
7687 /* struct {
7688 struct _objc_method_list *next_method;
7689 int method_count;
7690 struct _objc_method method_list[];
7691 }
7692 */
7693 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007694 Result += "\n";
7695 if (LangOpts.MicrosoftExt) {
7696 if (IsInstanceMethod)
7697 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7698 else
7699 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7700 }
7701 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007702 Result += "\tstruct _objc_method_list *next_method;\n";
7703 Result += "\tint method_count;\n";
7704 Result += "\tstruct _objc_method method_list[";
7705 Result += utostr(NumMethods);
7706 Result += "];\n} _OBJC_";
7707 Result += prefix;
7708 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7709 Result += "_METHODS_";
7710 Result += ClassName;
7711 Result += " __attribute__ ((used, section (\"__OBJC, __";
7712 Result += IsInstanceMethod ? "inst" : "cls";
7713 Result += "_meth\")))= ";
7714 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7715
7716 Result += "\t,{{(SEL)\"";
7717 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7718 std::string MethodTypeString;
7719 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7720 Result += "\", \"";
7721 Result += MethodTypeString;
7722 Result += "\", (void *)";
7723 Result += MethodInternalNames[*MethodBegin];
7724 Result += "}\n";
7725 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7726 Result += "\t ,{(SEL)\"";
7727 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7728 std::string MethodTypeString;
7729 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7730 Result += "\", \"";
7731 Result += MethodTypeString;
7732 Result += "\", (void *)";
7733 Result += MethodInternalNames[*MethodBegin];
7734 Result += "}\n";
7735 }
7736 Result += "\t }\n};\n";
7737}
7738
7739Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7740 SourceRange OldRange = IV->getSourceRange();
7741 Expr *BaseExpr = IV->getBase();
7742
7743 // Rewrite the base, but without actually doing replaces.
7744 {
7745 DisableReplaceStmtScope S(*this);
7746 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7747 IV->setBase(BaseExpr);
7748 }
7749
7750 ObjCIvarDecl *D = IV->getDecl();
7751
7752 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007753
Fariborz Jahanian11671902012-02-07 17:11:38 +00007754 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7755 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007756 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007757 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7758 // lookup which class implements the instance variable.
7759 ObjCInterfaceDecl *clsDeclared = 0;
7760 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7761 clsDeclared);
7762 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7763
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007764 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007765 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007766 if (D->isBitField())
7767 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7768 else
7769 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007770
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007771 ReferencedIvars[clsDeclared].insert(D);
7772
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007773 // cast offset to "char *".
7774 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7775 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007776 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007777 BaseExpr);
7778 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7779 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007780 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007781 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7782 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007783 SourceLocation());
7784 BinaryOperator *addExpr =
7785 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7786 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007787 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007788 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007789 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7790 SourceLocation(),
7791 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007792 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007793 if (D->isBitField())
7794 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007795
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007796 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007797 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007798 RD = RD->getDefinition();
7799 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007800 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007801 ObjCContainerDecl *CDecl =
7802 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7803 // ivar in class extensions requires special treatment.
7804 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7805 CDecl = CatDecl->getClassInterface();
7806 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007807 RecName += "_IMPL";
7808 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7809 SourceLocation(), SourceLocation(),
7810 &Context->Idents.get(RecName.c_str()));
7811 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7812 unsigned UnsignedIntSize =
7813 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7814 Expr *Zero = IntegerLiteral::Create(*Context,
7815 llvm::APInt(UnsignedIntSize, 0),
7816 Context->UnsignedIntTy, SourceLocation());
7817 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7818 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7819 Zero);
7820 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7821 SourceLocation(),
7822 &Context->Idents.get(D->getNameAsString()),
7823 IvarT, 0,
7824 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007825 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007826 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7827 FD->getType(), VK_LValue,
7828 OK_Ordinary);
7829 IvarT = Context->getDecltypeType(ME, ME->getType());
7830 }
7831 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007832 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007833 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007834
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007835 castExpr = NoTypeInfoCStyleCastExpr(Context,
7836 castT,
7837 CK_BitCast,
7838 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007839
7840
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007841 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007842 VK_LValue, OK_Ordinary,
7843 SourceLocation());
7844 PE = new (Context) ParenExpr(OldRange.getBegin(),
7845 OldRange.getEnd(),
7846 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007847
7848 if (D->isBitField()) {
7849 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7850 SourceLocation(),
7851 &Context->Idents.get(D->getNameAsString()),
7852 D->getType(), 0,
7853 /*BitWidth=*/D->getBitWidth(),
7854 /*Mutable=*/true,
7855 ICIS_NoInit);
7856 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7857 FD->getType(), VK_LValue,
7858 OK_Ordinary);
7859 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007860
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007861 }
7862 else
7863 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007864 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007865
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007866 ReplaceStmtWithRange(IV, Replacement, OldRange);
7867 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007868}