blob: f26c22615807e1e29ff82d42f38cbeb9cee37dbc [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 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000610
611 StringLiteral *getStringLiteral(StringRef Str) {
612 QualType StrType = Context->getConstantArrayType(
613 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
614 0);
615 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
616 /*Pascal=*/false, StrType, SourceLocation());
617 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000618 };
619
620}
621
622void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
623 NamedDecl *D) {
624 if (const FunctionProtoType *fproto
625 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000626 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
627 E = fproto->param_type_end();
628 I && (I != E); ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000629 if (isTopLevelBlockPointerType(*I)) {
630 // All the args are checked/rewritten. Don't call twice!
631 RewriteBlockPointerDecl(D);
632 break;
633 }
634 }
635}
636
637void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
638 const PointerType *PT = funcType->getAs<PointerType>();
639 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
640 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
641}
642
643static bool IsHeaderFile(const std::string &Filename) {
644 std::string::size_type DotPos = Filename.rfind('.');
645
646 if (DotPos == std::string::npos) {
647 // no file extension
648 return false;
649 }
650
651 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
652 // C header: .h
653 // C++ header: .hh or .H;
654 return Ext == "h" || Ext == "hh" || Ext == "H";
655}
656
657RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
658 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000659 bool silenceMacroWarn,
660 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000661 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000662 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000663 IsHeader = IsHeaderFile(inFile);
664 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
665 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000666 // FIXME. This should be an error. But if block is not called, it is OK. And it
667 // may break including some headers.
668 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
669 "rewriting block literal declared in global scope is not implemented");
670
Fariborz Jahanian11671902012-02-07 17:11:38 +0000671 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
672 DiagnosticsEngine::Warning,
673 "rewriter doesn't support user-specified control flow semantics "
674 "for @try/@finally (code may not execute properly)");
675}
676
677ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
678 raw_ostream* OS,
679 DiagnosticsEngine &Diags,
680 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000681 bool SilenceRewriteMacroWarning,
682 bool LineInfo) {
683 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
684 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000685}
686
687void RewriteModernObjC::InitializeCommon(ASTContext &context) {
688 Context = &context;
689 SM = &Context->getSourceManager();
690 TUDecl = Context->getTranslationUnitDecl();
691 MsgSendFunctionDecl = 0;
692 MsgSendSuperFunctionDecl = 0;
693 MsgSendStretFunctionDecl = 0;
694 MsgSendSuperStretFunctionDecl = 0;
695 MsgSendFpretFunctionDecl = 0;
696 GetClassFunctionDecl = 0;
697 GetMetaClassFunctionDecl = 0;
698 GetSuperClassFunctionDecl = 0;
699 SelGetUidFunctionDecl = 0;
700 CFStringFunctionDecl = 0;
701 ConstantStringClassReference = 0;
702 NSStringRecord = 0;
703 CurMethodDef = 0;
704 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000705 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000706 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000707 SuperStructDecl = 0;
708 ProtocolTypeDecl = 0;
709 ConstantStringDecl = 0;
710 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000711 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000712 NumObjCStringLiterals = 0;
713 PropParentMap = 0;
714 CurrentBody = 0;
715 DisableReplaceStmt = false;
716 objc_impl_method = false;
717
718 // Get the ID and start/end of the main file.
719 MainFileID = SM->getMainFileID();
720 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
721 MainFileStart = MainBuf->getBufferStart();
722 MainFileEnd = MainBuf->getBufferEnd();
723
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000725}
726
727//===----------------------------------------------------------------------===//
728// Top Level Driver Code
729//===----------------------------------------------------------------------===//
730
731void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
732 if (Diags.hasErrorOccurred())
733 return;
734
735 // Two cases: either the decl could be in the main file, or it could be in a
736 // #included file. If the former, rewrite it now. If the later, check to see
737 // if we rewrote the #include/#import.
738 SourceLocation Loc = D->getLocation();
739 Loc = SM->getExpansionLoc(Loc);
740
741 // If this is for a builtin, ignore it.
742 if (Loc.isInvalid()) return;
743
744 // Look for built-in declarations that we need to refer during the rewrite.
745 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
746 RewriteFunctionDecl(FD);
747 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
748 // declared in <Foundation/NSString.h>
749 if (FVD->getName() == "_NSConstantStringClassReference") {
750 ConstantStringClassReference = FVD;
751 return;
752 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000753 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
754 RewriteCategoryDecl(CD);
755 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
756 if (PD->isThisDeclarationADefinition())
757 RewriteProtocolDecl(PD);
758 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000759 // FIXME. This will not work in all situations and leaving it out
760 // is harmless.
761 // RewriteLinkageSpec(LSD);
762
Fariborz Jahanian11671902012-02-07 17:11:38 +0000763 // Recurse into linkage specifications
764 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
765 DIEnd = LSD->decls_end();
766 DI != DIEnd; ) {
767 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
768 if (!IFace->isThisDeclarationADefinition()) {
769 SmallVector<Decl *, 8> DG;
770 SourceLocation StartLoc = IFace->getLocStart();
771 do {
772 if (isa<ObjCInterfaceDecl>(*DI) &&
773 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
774 StartLoc == (*DI)->getLocStart())
775 DG.push_back(*DI);
776 else
777 break;
778
779 ++DI;
780 } while (DI != DIEnd);
781 RewriteForwardClassDecl(DG);
782 continue;
783 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000784 else {
785 // Keep track of all interface declarations seen.
786 ObjCInterfacesSeen.push_back(IFace);
787 ++DI;
788 continue;
789 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000790 }
791
792 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
793 if (!Proto->isThisDeclarationADefinition()) {
794 SmallVector<Decl *, 8> DG;
795 SourceLocation StartLoc = Proto->getLocStart();
796 do {
797 if (isa<ObjCProtocolDecl>(*DI) &&
798 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
799 StartLoc == (*DI)->getLocStart())
800 DG.push_back(*DI);
801 else
802 break;
803
804 ++DI;
805 } while (DI != DIEnd);
806 RewriteForwardProtocolDecl(DG);
807 continue;
808 }
809 }
810
811 HandleTopLevelSingleDecl(*DI);
812 ++DI;
813 }
814 }
815 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000816 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000817 return HandleDeclInMainFile(D);
818}
819
820//===----------------------------------------------------------------------===//
821// Syntactic (non-AST) Rewriting Code
822//===----------------------------------------------------------------------===//
823
824void RewriteModernObjC::RewriteInclude() {
825 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
826 StringRef MainBuf = SM->getBufferData(MainFileID);
827 const char *MainBufStart = MainBuf.begin();
828 const char *MainBufEnd = MainBuf.end();
829 size_t ImportLen = strlen("import");
830
831 // Loop over the whole file, looking for includes.
832 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
833 if (*BufPtr == '#') {
834 if (++BufPtr == MainBufEnd)
835 return;
836 while (*BufPtr == ' ' || *BufPtr == '\t')
837 if (++BufPtr == MainBufEnd)
838 return;
839 if (!strncmp(BufPtr, "import", ImportLen)) {
840 // replace import with include
841 SourceLocation ImportLoc =
842 LocStart.getLocWithOffset(BufPtr-MainBufStart);
843 ReplaceText(ImportLoc, ImportLen, "include");
844 BufPtr += ImportLen;
845 }
846 }
847 }
848}
849
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000850static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
851 ObjCIvarDecl *IvarDecl, std::string &Result) {
852 Result += "OBJC_IVAR_$_";
853 Result += IDecl->getName();
854 Result += "$";
855 Result += IvarDecl->getName();
856}
857
858std::string
859RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
860 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
861
862 // Build name of symbol holding ivar offset.
863 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000864 if (D->isBitField())
865 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
866 else
867 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000868
869
870 std::string S = "(*(";
871 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000872 if (D->isBitField())
873 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000874
875 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
876 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
877 RD = RD->getDefinition();
878 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
879 // decltype(((Foo_IMPL*)0)->bar) *
880 ObjCContainerDecl *CDecl =
881 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
882 // ivar in class extensions requires special treatment.
883 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
884 CDecl = CatDecl->getClassInterface();
885 std::string RecName = CDecl->getName();
886 RecName += "_IMPL";
887 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
888 SourceLocation(), SourceLocation(),
889 &Context->Idents.get(RecName.c_str()));
890 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
891 unsigned UnsignedIntSize =
892 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
893 Expr *Zero = IntegerLiteral::Create(*Context,
894 llvm::APInt(UnsignedIntSize, 0),
895 Context->UnsignedIntTy, SourceLocation());
896 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
897 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
898 Zero);
899 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
900 SourceLocation(),
901 &Context->Idents.get(D->getNameAsString()),
902 IvarT, 0,
903 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000904 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000905 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
906 FD->getType(), VK_LValue,
907 OK_Ordinary);
908 IvarT = Context->getDecltypeType(ME, ME->getType());
909 }
910 }
911 convertObjCTypeToCStyleType(IvarT);
912 QualType castT = Context->getPointerType(IvarT);
913 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
914 S += TypeString;
915 S += ")";
916
917 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
918 S += "((char *)self + ";
919 S += IvarOffsetName;
920 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000921 if (D->isBitField()) {
922 S += ".";
923 S += D->getNameAsString();
924 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000925 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000926 return S;
927}
928
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000929/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
930/// been found in the class implementation. In this case, it must be synthesized.
931static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
932 ObjCPropertyDecl *PD,
933 bool getter) {
934 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
935 : !IMP->getInstanceMethod(PD->getSetterName());
936
937}
938
Fariborz Jahanian11671902012-02-07 17:11:38 +0000939void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
940 ObjCImplementationDecl *IMD,
941 ObjCCategoryImplDecl *CID) {
942 static bool objcGetPropertyDefined = false;
943 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000944 SourceLocation startGetterSetterLoc;
945
946 if (PID->getLocStart().isValid()) {
947 SourceLocation startLoc = PID->getLocStart();
948 InsertText(startLoc, "// ");
949 const char *startBuf = SM->getCharacterData(startLoc);
950 assert((*startBuf == '@') && "bogus @synthesize location");
951 const char *semiBuf = strchr(startBuf, ';');
952 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
953 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
954 }
955 else
956 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957
958 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
959 return; // FIXME: is this correct?
960
961 // Generate the 'getter' function.
962 ObjCPropertyDecl *PD = PID->getPropertyDecl();
963 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000964 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000965
Bill Wendling44426052012-12-20 19:22:21 +0000966 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000967 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000968 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
969 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000970 ObjCPropertyDecl::OBJC_PR_copy));
971 std::string Getr;
972 if (GenGetProperty && !objcGetPropertyDefined) {
973 objcGetPropertyDefined = true;
974 // FIXME. Is this attribute correct in all cases?
975 Getr = "\nextern \"C\" __declspec(dllimport) "
976 "id objc_getProperty(id, SEL, long, bool);\n";
977 }
978 RewriteObjCMethodDecl(OID->getContainingInterface(),
979 PD->getGetterMethodDecl(), Getr);
980 Getr += "{ ";
981 // Synthesize an explicit cast to gain access to the ivar.
982 // See objc-act.c:objc_synthesize_new_getter() for details.
983 if (GenGetProperty) {
984 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
985 Getr += "typedef ";
986 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000987 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000988 FPRetType);
989 Getr += " _TYPE";
990 if (FPRetType) {
991 Getr += ")"; // close the precedence "scope" for "*".
992
993 // Now, emit the argument types (if any).
994 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
995 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000998 std::string ParamStr =
999 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001000 Getr += ParamStr;
1001 }
1002 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001003 if (FT->getNumParams())
1004 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001005 Getr += "...";
1006 }
1007 Getr += ")";
1008 } else
1009 Getr += "()";
1010 }
1011 Getr += ";\n";
1012 Getr += "return (_TYPE)";
1013 Getr += "objc_getProperty(self, _cmd, ";
1014 RewriteIvarOffsetComputation(OID, Getr);
1015 Getr += ", 1)";
1016 }
1017 else
1018 Getr += "return " + getIvarAccessString(OID);
1019 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001020 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001021 }
1022
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001023 if (PD->isReadOnly() ||
1024 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001025 return;
1026
1027 // Generate the 'setter' function.
1028 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001029 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001030 ObjCPropertyDecl::OBJC_PR_copy);
1031 if (GenSetProperty && !objcSetPropertyDefined) {
1032 objcSetPropertyDefined = true;
1033 // FIXME. Is this attribute correct in all cases?
1034 Setr = "\nextern \"C\" __declspec(dllimport) "
1035 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1036 }
1037
1038 RewriteObjCMethodDecl(OID->getContainingInterface(),
1039 PD->getSetterMethodDecl(), Setr);
1040 Setr += "{ ";
1041 // Synthesize an explicit cast to initialize the ivar.
1042 // See objc-act.c:objc_synthesize_new_setter() for details.
1043 if (GenSetProperty) {
1044 Setr += "objc_setProperty (self, _cmd, ";
1045 RewriteIvarOffsetComputation(OID, Setr);
1046 Setr += ", (id)";
1047 Setr += PD->getName();
1048 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001049 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001050 Setr += "0, ";
1051 else
1052 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001053 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001054 Setr += "1)";
1055 else
1056 Setr += "0)";
1057 }
1058 else {
1059 Setr += getIvarAccessString(OID) + " = ";
1060 Setr += PD->getName();
1061 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001062 Setr += "; }\n";
1063 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001064}
1065
1066static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1067 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001068 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001069 typedefString += ForwardDecl->getNameAsString();
1070 typedefString += "\n";
1071 typedefString += "#define _REWRITER_typedef_";
1072 typedefString += ForwardDecl->getNameAsString();
1073 typedefString += "\n";
1074 typedefString += "typedef struct objc_object ";
1075 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001076 // typedef struct { } _objc_exc_Classname;
1077 typedefString += ";\ntypedef struct {} _objc_exc_";
1078 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001079 typedefString += ";\n#endif\n";
1080}
1081
1082void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1083 const std::string &typedefString) {
1084 SourceLocation startLoc = ClassDecl->getLocStart();
1085 const char *startBuf = SM->getCharacterData(startLoc);
1086 const char *semiPtr = strchr(startBuf, ';');
1087 // Replace the @class with typedefs corresponding to the classes.
1088 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1089}
1090
1091void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1092 std::string typedefString;
1093 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001094 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1095 if (I == D.begin()) {
1096 // Translate to typedef's that forward reference structs with the same name
1097 // as the class. As a convenience, we include the original declaration
1098 // as a comment.
1099 typedefString += "// @class ";
1100 typedefString += ForwardDecl->getNameAsString();
1101 typedefString += ";";
1102 }
1103 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001104 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001105 else
1106 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001107 }
1108 DeclGroupRef::iterator I = D.begin();
1109 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1110}
1111
1112void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001113 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001114 std::string typedefString;
1115 for (unsigned i = 0; i < D.size(); i++) {
1116 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1117 if (i == 0) {
1118 typedefString += "// @class ";
1119 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001120 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001121 }
1122 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1123 }
1124 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1125}
1126
1127void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1128 // When method is a synthesized one, such as a getter/setter there is
1129 // nothing to rewrite.
1130 if (Method->isImplicit())
1131 return;
1132 SourceLocation LocStart = Method->getLocStart();
1133 SourceLocation LocEnd = Method->getLocEnd();
1134
1135 if (SM->getExpansionLineNumber(LocEnd) >
1136 SM->getExpansionLineNumber(LocStart)) {
1137 InsertText(LocStart, "#if 0\n");
1138 ReplaceText(LocEnd, 1, ";\n#endif\n");
1139 } else {
1140 InsertText(LocStart, "// ");
1141 }
1142}
1143
1144void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1145 SourceLocation Loc = prop->getAtLoc();
1146
1147 ReplaceText(Loc, 0, "// ");
1148 // FIXME: handle properties that are declared across multiple lines.
1149}
1150
1151void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1152 SourceLocation LocStart = CatDecl->getLocStart();
1153
1154 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001155 if (CatDecl->getIvarRBraceLoc().isValid()) {
1156 ReplaceText(LocStart, 1, "/** ");
1157 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1158 }
1159 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001160 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001161 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001162
Fariborz Jahanian11671902012-02-07 17:11:38 +00001163 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1164 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001165 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001166
1167 for (ObjCCategoryDecl::instmeth_iterator
1168 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1169 I != E; ++I)
1170 RewriteMethodDeclaration(*I);
1171 for (ObjCCategoryDecl::classmeth_iterator
1172 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1173 I != E; ++I)
1174 RewriteMethodDeclaration(*I);
1175
1176 // Lastly, comment out the @end.
1177 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001178 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001179}
1180
1181void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1182 SourceLocation LocStart = PDecl->getLocStart();
1183 assert(PDecl->isThisDeclarationADefinition());
1184
1185 // FIXME: handle protocol headers that are declared across multiple lines.
1186 ReplaceText(LocStart, 0, "// ");
1187
1188 for (ObjCProtocolDecl::instmeth_iterator
1189 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1190 I != E; ++I)
1191 RewriteMethodDeclaration(*I);
1192 for (ObjCProtocolDecl::classmeth_iterator
1193 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1194 I != E; ++I)
1195 RewriteMethodDeclaration(*I);
1196
1197 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1198 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001199 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001200
1201 // Lastly, comment out the @end.
1202 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001203 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001204
1205 // Must comment out @optional/@required
1206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
1208 for (const char *p = startBuf; p < endBuf; p++) {
1209 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1210 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1211 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1212
1213 }
1214 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1215 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1216 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1217
1218 }
1219 }
1220}
1221
1222void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1223 SourceLocation LocStart = (*D.begin())->getLocStart();
1224 if (LocStart.isInvalid())
1225 llvm_unreachable("Invalid SourceLocation");
1226 // FIXME: handle forward protocol that are declared across multiple lines.
1227 ReplaceText(LocStart, 0, "// ");
1228}
1229
1230void
Craig Topper5603df42013-07-05 19:34:19 +00001231RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001232 SourceLocation LocStart = DG[0]->getLocStart();
1233 if (LocStart.isInvalid())
1234 llvm_unreachable("Invalid SourceLocation");
1235 // FIXME: handle forward protocol that are declared across multiple lines.
1236 ReplaceText(LocStart, 0, "// ");
1237}
1238
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001239void
1240RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1241 SourceLocation LocStart = LSD->getExternLoc();
1242 if (LocStart.isInvalid())
1243 llvm_unreachable("Invalid extern SourceLocation");
1244
1245 ReplaceText(LocStart, 0, "// ");
1246 if (!LSD->hasBraces())
1247 return;
1248 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1249 SourceLocation LocRBrace = LSD->getRBraceLoc();
1250 if (LocRBrace.isInvalid())
1251 llvm_unreachable("Invalid rbrace SourceLocation");
1252 ReplaceText(LocRBrace, 0, "// ");
1253}
1254
Fariborz Jahanian11671902012-02-07 17:11:38 +00001255void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1256 const FunctionType *&FPRetType) {
1257 if (T->isObjCQualifiedIdType())
1258 ResultStr += "id";
1259 else if (T->isFunctionPointerType() ||
1260 T->isBlockPointerType()) {
1261 // needs special handling, since pointer-to-functions have special
1262 // syntax (where a decaration models use).
1263 QualType retType = T;
1264 QualType PointeeTy;
1265 if (const PointerType* PT = retType->getAs<PointerType>())
1266 PointeeTy = PT->getPointeeType();
1267 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1268 PointeeTy = BPT->getPointeeType();
1269 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001270 ResultStr +=
1271 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001272 ResultStr += "(*";
1273 }
1274 } else
1275 ResultStr += T.getAsString(Context->getPrintingPolicy());
1276}
1277
1278void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1279 ObjCMethodDecl *OMD,
1280 std::string &ResultStr) {
1281 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1282 const FunctionType *FPRetType = 0;
1283 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001284 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001285 ResultStr += " ";
1286
1287 // Unique method name
1288 std::string NameStr;
1289
1290 if (OMD->isInstanceMethod())
1291 NameStr += "_I_";
1292 else
1293 NameStr += "_C_";
1294
1295 NameStr += IDecl->getNameAsString();
1296 NameStr += "_";
1297
1298 if (ObjCCategoryImplDecl *CID =
1299 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1300 NameStr += CID->getNameAsString();
1301 NameStr += "_";
1302 }
1303 // Append selector names, replacing ':' with '_'
1304 {
1305 std::string selString = OMD->getSelector().getAsString();
1306 int len = selString.size();
1307 for (int i = 0; i < len; i++)
1308 if (selString[i] == ':')
1309 selString[i] = '_';
1310 NameStr += selString;
1311 }
1312 // Remember this name for metadata emission
1313 MethodInternalNames[OMD] = NameStr;
1314 ResultStr += NameStr;
1315
1316 // Rewrite arguments
1317 ResultStr += "(";
1318
1319 // invisible arguments
1320 if (OMD->isInstanceMethod()) {
1321 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1322 selfTy = Context->getPointerType(selfTy);
1323 if (!LangOpts.MicrosoftExt) {
1324 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1325 ResultStr += "struct ";
1326 }
1327 // When rewriting for Microsoft, explicitly omit the structure name.
1328 ResultStr += IDecl->getNameAsString();
1329 ResultStr += " *";
1330 }
1331 else
1332 ResultStr += Context->getObjCClassType().getAsString(
1333 Context->getPrintingPolicy());
1334
1335 ResultStr += " self, ";
1336 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1337 ResultStr += " _cmd";
1338
1339 // Method arguments.
1340 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1341 E = OMD->param_end(); PI != E; ++PI) {
1342 ParmVarDecl *PDecl = *PI;
1343 ResultStr += ", ";
1344 if (PDecl->getType()->isObjCQualifiedIdType()) {
1345 ResultStr += "id ";
1346 ResultStr += PDecl->getNameAsString();
1347 } else {
1348 std::string Name = PDecl->getNameAsString();
1349 QualType QT = PDecl->getType();
1350 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001351 (void)convertBlockPointerToFunctionPointer(QT);
1352 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001353 ResultStr += Name;
1354 }
1355 }
1356 if (OMD->isVariadic())
1357 ResultStr += ", ...";
1358 ResultStr += ") ";
1359
1360 if (FPRetType) {
1361 ResultStr += ")"; // close the precedence "scope" for "*".
1362
1363 // Now, emit the argument types (if any).
1364 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1365 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001366 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001367 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001368 std::string ParamStr =
1369 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001370 ResultStr += ParamStr;
1371 }
1372 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001373 if (FT->getNumParams())
1374 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001375 ResultStr += "...";
1376 }
1377 ResultStr += ")";
1378 } else {
1379 ResultStr += "()";
1380 }
1381 }
1382}
1383void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1384 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1385 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1386
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001387 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001388 if (IMD->getIvarRBraceLoc().isValid()) {
1389 ReplaceText(IMD->getLocStart(), 1, "/** ");
1390 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001391 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001392 else {
1393 InsertText(IMD->getLocStart(), "// ");
1394 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001395 }
1396 else
1397 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001398
1399 for (ObjCCategoryImplDecl::instmeth_iterator
1400 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1401 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1402 I != E; ++I) {
1403 std::string ResultStr;
1404 ObjCMethodDecl *OMD = *I;
1405 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1406 SourceLocation LocStart = OMD->getLocStart();
1407 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1408
1409 const char *startBuf = SM->getCharacterData(LocStart);
1410 const char *endBuf = SM->getCharacterData(LocEnd);
1411 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1412 }
1413
1414 for (ObjCCategoryImplDecl::classmeth_iterator
1415 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1416 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1417 I != E; ++I) {
1418 std::string ResultStr;
1419 ObjCMethodDecl *OMD = *I;
1420 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1421 SourceLocation LocStart = OMD->getLocStart();
1422 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1423
1424 const char *startBuf = SM->getCharacterData(LocStart);
1425 const char *endBuf = SM->getCharacterData(LocEnd);
1426 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1427 }
1428 for (ObjCCategoryImplDecl::propimpl_iterator
1429 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1430 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1431 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001432 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001433 }
1434
1435 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1436}
1437
1438void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001439 // Do not synthesize more than once.
1440 if (ObjCSynthesizedStructs.count(ClassDecl))
1441 return;
1442 // Make sure super class's are written before current class is written.
1443 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1444 while (SuperClass) {
1445 RewriteInterfaceDecl(SuperClass);
1446 SuperClass = SuperClass->getSuperClass();
1447 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001448 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001449 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001450 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001451 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001452 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1453
Fariborz Jahanianff513382012-02-15 22:01:47 +00001454 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001455 // Mark this typedef as having been written into its c++ equivalent.
1456 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001457
1458 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001459 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001460 RewriteProperty(*I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001461 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001462 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001463 I != E; ++I)
1464 RewriteMethodDeclaration(*I);
1465 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001466 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001467 I != E; ++I)
1468 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001469
Fariborz Jahanianff513382012-02-15 22:01:47 +00001470 // Lastly, comment out the @end.
1471 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001472 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001473 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001474}
1475
1476Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1477 SourceRange OldRange = PseudoOp->getSourceRange();
1478
1479 // We just magically know some things about the structure of this
1480 // expression.
1481 ObjCMessageExpr *OldMsg =
1482 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1483 PseudoOp->getNumSemanticExprs() - 1));
1484
1485 // Because the rewriter doesn't allow us to rewrite rewritten code,
1486 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001487 Expr *Base;
1488 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001489 {
1490 DisableReplaceStmtScope S(*this);
1491
1492 // Rebuild the base expression if we have one.
1493 Base = 0;
1494 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1495 Base = OldMsg->getInstanceReceiver();
1496 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1497 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1498 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001499
1500 unsigned numArgs = OldMsg->getNumArgs();
1501 for (unsigned i = 0; i < numArgs; i++) {
1502 Expr *Arg = OldMsg->getArg(i);
1503 if (isa<OpaqueValueExpr>(Arg))
1504 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1505 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1506 Args.push_back(Arg);
1507 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001508 }
1509
1510 // TODO: avoid this copy.
1511 SmallVector<SourceLocation, 1> SelLocs;
1512 OldMsg->getSelectorLocs(SelLocs);
1513
1514 ObjCMessageExpr *NewMsg = 0;
1515 switch (OldMsg->getReceiverKind()) {
1516 case ObjCMessageExpr::Class:
1517 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1518 OldMsg->getValueKind(),
1519 OldMsg->getLeftLoc(),
1520 OldMsg->getClassReceiverTypeInfo(),
1521 OldMsg->getSelector(),
1522 SelLocs,
1523 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001524 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001525 OldMsg->getRightLoc(),
1526 OldMsg->isImplicit());
1527 break;
1528
1529 case ObjCMessageExpr::Instance:
1530 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1531 OldMsg->getValueKind(),
1532 OldMsg->getLeftLoc(),
1533 Base,
1534 OldMsg->getSelector(),
1535 SelLocs,
1536 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001537 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001538 OldMsg->getRightLoc(),
1539 OldMsg->isImplicit());
1540 break;
1541
1542 case ObjCMessageExpr::SuperClass:
1543 case ObjCMessageExpr::SuperInstance:
1544 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1545 OldMsg->getValueKind(),
1546 OldMsg->getLeftLoc(),
1547 OldMsg->getSuperLoc(),
1548 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1549 OldMsg->getSuperType(),
1550 OldMsg->getSelector(),
1551 SelLocs,
1552 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001553 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001554 OldMsg->getRightLoc(),
1555 OldMsg->isImplicit());
1556 break;
1557 }
1558
1559 Stmt *Replacement = SynthMessageExpr(NewMsg);
1560 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1561 return Replacement;
1562}
1563
1564Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1565 SourceRange OldRange = PseudoOp->getSourceRange();
1566
1567 // We just magically know some things about the structure of this
1568 // expression.
1569 ObjCMessageExpr *OldMsg =
1570 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1571
1572 // Because the rewriter doesn't allow us to rewrite rewritten code,
1573 // we need to suppress rewriting the sub-statements.
1574 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001575 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001576 {
1577 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001578 // Rebuild the base expression if we have one.
1579 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1580 Base = OldMsg->getInstanceReceiver();
1581 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1582 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1583 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001584 unsigned numArgs = OldMsg->getNumArgs();
1585 for (unsigned i = 0; i < numArgs; i++) {
1586 Expr *Arg = OldMsg->getArg(i);
1587 if (isa<OpaqueValueExpr>(Arg))
1588 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1589 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1590 Args.push_back(Arg);
1591 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001592 }
1593
1594 // Intentionally empty.
1595 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001596
1597 ObjCMessageExpr *NewMsg = 0;
1598 switch (OldMsg->getReceiverKind()) {
1599 case ObjCMessageExpr::Class:
1600 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1601 OldMsg->getValueKind(),
1602 OldMsg->getLeftLoc(),
1603 OldMsg->getClassReceiverTypeInfo(),
1604 OldMsg->getSelector(),
1605 SelLocs,
1606 OldMsg->getMethodDecl(),
1607 Args,
1608 OldMsg->getRightLoc(),
1609 OldMsg->isImplicit());
1610 break;
1611
1612 case ObjCMessageExpr::Instance:
1613 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1614 OldMsg->getValueKind(),
1615 OldMsg->getLeftLoc(),
1616 Base,
1617 OldMsg->getSelector(),
1618 SelLocs,
1619 OldMsg->getMethodDecl(),
1620 Args,
1621 OldMsg->getRightLoc(),
1622 OldMsg->isImplicit());
1623 break;
1624
1625 case ObjCMessageExpr::SuperClass:
1626 case ObjCMessageExpr::SuperInstance:
1627 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1628 OldMsg->getValueKind(),
1629 OldMsg->getLeftLoc(),
1630 OldMsg->getSuperLoc(),
1631 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1632 OldMsg->getSuperType(),
1633 OldMsg->getSelector(),
1634 SelLocs,
1635 OldMsg->getMethodDecl(),
1636 Args,
1637 OldMsg->getRightLoc(),
1638 OldMsg->isImplicit());
1639 break;
1640 }
1641
1642 Stmt *Replacement = SynthMessageExpr(NewMsg);
1643 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1644 return Replacement;
1645}
1646
1647/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001648/// ((NSUInteger (*)
1649/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001650/// (void *)objc_msgSend)((id)l_collection,
1651/// sel_registerName(
1652/// "countByEnumeratingWithState:objects:count:"),
1653/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001654/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001655///
1656void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001657 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1658 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001659 buf += "\n\t\t";
1660 buf += "((id)l_collection,\n\t\t";
1661 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1662 buf += "\n\t\t";
1663 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001664 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001665}
1666
1667/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1668/// statement to exit to its outer synthesized loop.
1669///
1670Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1671 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1672 return S;
1673 // replace break with goto __break_label
1674 std::string buf;
1675
1676 SourceLocation startLoc = S->getLocStart();
1677 buf = "goto __break_label_";
1678 buf += utostr(ObjCBcLabelNo.back());
1679 ReplaceText(startLoc, strlen("break"), buf);
1680
1681 return 0;
1682}
1683
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001684void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1685 SourceLocation Loc,
1686 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001687 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001688 LineString += "\n#line ";
1689 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1690 LineString += utostr(PLoc.getLine());
1691 LineString += " \"";
1692 LineString += Lexer::Stringify(PLoc.getFilename());
1693 LineString += "\"\n";
1694 }
1695}
1696
Fariborz Jahanian11671902012-02-07 17:11:38 +00001697/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1698/// statement to continue with its inner synthesized loop.
1699///
1700Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1701 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1702 return S;
1703 // replace continue with goto __continue_label
1704 std::string buf;
1705
1706 SourceLocation startLoc = S->getLocStart();
1707 buf = "goto __continue_label_";
1708 buf += utostr(ObjCBcLabelNo.back());
1709 ReplaceText(startLoc, strlen("continue"), buf);
1710
1711 return 0;
1712}
1713
1714/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1715/// It rewrites:
1716/// for ( type elem in collection) { stmts; }
1717
1718/// Into:
1719/// {
1720/// type elem;
1721/// struct __objcFastEnumerationState enumState = { 0 };
1722/// id __rw_items[16];
1723/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001724/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001725/// objects:__rw_items count:16];
1726/// if (limit) {
1727/// unsigned long startMutations = *enumState.mutationsPtr;
1728/// do {
1729/// unsigned long counter = 0;
1730/// do {
1731/// if (startMutations != *enumState.mutationsPtr)
1732/// objc_enumerationMutation(l_collection);
1733/// elem = (type)enumState.itemsPtr[counter++];
1734/// stmts;
1735/// __continue_label: ;
1736/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001737/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1738/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001739/// elem = nil;
1740/// __break_label: ;
1741/// }
1742/// else
1743/// elem = nil;
1744/// }
1745///
1746Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1747 SourceLocation OrigEnd) {
1748 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1749 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1750 "ObjCForCollectionStmt Statement stack mismatch");
1751 assert(!ObjCBcLabelNo.empty() &&
1752 "ObjCForCollectionStmt - Label No stack empty");
1753
1754 SourceLocation startLoc = S->getLocStart();
1755 const char *startBuf = SM->getCharacterData(startLoc);
1756 StringRef elementName;
1757 std::string elementTypeAsString;
1758 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001759 // line directive first.
1760 SourceLocation ForEachLoc = S->getForLoc();
1761 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1762 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001763 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1764 // type elem;
1765 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1766 QualType ElementType = cast<ValueDecl>(D)->getType();
1767 if (ElementType->isObjCQualifiedIdType() ||
1768 ElementType->isObjCQualifiedInterfaceType())
1769 // Simply use 'id' for all qualified types.
1770 elementTypeAsString = "id";
1771 else
1772 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1773 buf += elementTypeAsString;
1774 buf += " ";
1775 elementName = D->getName();
1776 buf += elementName;
1777 buf += ";\n\t";
1778 }
1779 else {
1780 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1781 elementName = DR->getDecl()->getName();
1782 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1783 if (VD->getType()->isObjCQualifiedIdType() ||
1784 VD->getType()->isObjCQualifiedInterfaceType())
1785 // Simply use 'id' for all qualified types.
1786 elementTypeAsString = "id";
1787 else
1788 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1789 }
1790
1791 // struct __objcFastEnumerationState enumState = { 0 };
1792 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1793 // id __rw_items[16];
1794 buf += "id __rw_items[16];\n\t";
1795 // id l_collection = (id)
1796 buf += "id l_collection = (id)";
1797 // Find start location of 'collection' the hard way!
1798 const char *startCollectionBuf = startBuf;
1799 startCollectionBuf += 3; // skip 'for'
1800 startCollectionBuf = strchr(startCollectionBuf, '(');
1801 startCollectionBuf++; // skip '('
1802 // find 'in' and skip it.
1803 while (*startCollectionBuf != ' ' ||
1804 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1805 (*(startCollectionBuf+3) != ' ' &&
1806 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1807 startCollectionBuf++;
1808 startCollectionBuf += 3;
1809
1810 // Replace: "for (type element in" with string constructed thus far.
1811 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1812 // Replace ')' in for '(' type elem in collection ')' with ';'
1813 SourceLocation rightParenLoc = S->getRParenLoc();
1814 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1815 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1816 buf = ";\n\t";
1817
1818 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1819 // objects:__rw_items count:16];
1820 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001821 // NSUInteger limit =
1822 // ((NSUInteger (*)
1823 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001824 // (void *)objc_msgSend)((id)l_collection,
1825 // sel_registerName(
1826 // "countByEnumeratingWithState:objects:count:"),
1827 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001828 // (id *)__rw_items, (NSUInteger)16);
1829 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001830 SynthCountByEnumWithState(buf);
1831 buf += ";\n\t";
1832 /// if (limit) {
1833 /// unsigned long startMutations = *enumState.mutationsPtr;
1834 /// do {
1835 /// unsigned long counter = 0;
1836 /// do {
1837 /// if (startMutations != *enumState.mutationsPtr)
1838 /// objc_enumerationMutation(l_collection);
1839 /// elem = (type)enumState.itemsPtr[counter++];
1840 buf += "if (limit) {\n\t";
1841 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1842 buf += "do {\n\t\t";
1843 buf += "unsigned long counter = 0;\n\t\t";
1844 buf += "do {\n\t\t\t";
1845 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1846 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1847 buf += elementName;
1848 buf += " = (";
1849 buf += elementTypeAsString;
1850 buf += ")enumState.itemsPtr[counter++];";
1851 // Replace ')' in for '(' type elem in collection ')' with all of these.
1852 ReplaceText(lparenLoc, 1, buf);
1853
1854 /// __continue_label: ;
1855 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001856 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1857 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001858 /// elem = nil;
1859 /// __break_label: ;
1860 /// }
1861 /// else
1862 /// elem = nil;
1863 /// }
1864 ///
1865 buf = ";\n\t";
1866 buf += "__continue_label_";
1867 buf += utostr(ObjCBcLabelNo.back());
1868 buf += ": ;";
1869 buf += "\n\t\t";
1870 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001871 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001872 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001873 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001874 buf += elementName;
1875 buf += " = ((";
1876 buf += elementTypeAsString;
1877 buf += ")0);\n\t";
1878 buf += "__break_label_";
1879 buf += utostr(ObjCBcLabelNo.back());
1880 buf += ": ;\n\t";
1881 buf += "}\n\t";
1882 buf += "else\n\t\t";
1883 buf += elementName;
1884 buf += " = ((";
1885 buf += elementTypeAsString;
1886 buf += ")0);\n\t";
1887 buf += "}\n";
1888
1889 // Insert all these *after* the statement body.
1890 // FIXME: If this should support Obj-C++, support CXXTryStmt
1891 if (isa<CompoundStmt>(S->getBody())) {
1892 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1893 InsertText(endBodyLoc, buf);
1894 } else {
1895 /* Need to treat single statements specially. For example:
1896 *
1897 * for (A *a in b) if (stuff()) break;
1898 * for (A *a in b) xxxyy;
1899 *
1900 * The following code simply scans ahead to the semi to find the actual end.
1901 */
1902 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1903 const char *semiBuf = strchr(stmtBuf, ';');
1904 assert(semiBuf && "Can't find ';'");
1905 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1906 InsertText(endBodyLoc, buf);
1907 }
1908 Stmts.pop_back();
1909 ObjCBcLabelNo.pop_back();
1910 return 0;
1911}
1912
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001913static void Write_RethrowObject(std::string &buf) {
1914 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1915 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1916 buf += "\tid rethrow;\n";
1917 buf += "\t} _fin_force_rethow(_rethrow);";
1918}
1919
Fariborz Jahanian11671902012-02-07 17:11:38 +00001920/// RewriteObjCSynchronizedStmt -
1921/// This routine rewrites @synchronized(expr) stmt;
1922/// into:
1923/// objc_sync_enter(expr);
1924/// @try stmt @finally { objc_sync_exit(expr); }
1925///
1926Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1927 // Get the start location and compute the semi location.
1928 SourceLocation startLoc = S->getLocStart();
1929 const char *startBuf = SM->getCharacterData(startLoc);
1930
1931 assert((*startBuf == '@') && "bogus @synchronized location");
1932
1933 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001934 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1935 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001936 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001937
Fariborz Jahanian11671902012-02-07 17:11:38 +00001938 const char *lparenBuf = startBuf;
1939 while (*lparenBuf != '(') lparenBuf++;
1940 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001941
1942 buf = "; objc_sync_enter(_sync_obj);\n";
1943 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1944 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1945 buf += "\n\tid sync_exit;";
1946 buf += "\n\t} _sync_exit(_sync_obj);\n";
1947
1948 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1949 // the sync expression is typically a message expression that's already
1950 // been rewritten! (which implies the SourceLocation's are invalid).
1951 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1952 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1953 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1954 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1955
1956 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1957 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1958 assert (*LBraceLocBuf == '{');
1959 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001960
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001961 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001962 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1963 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001964
1965 buf = "} catch (id e) {_rethrow = e;}\n";
1966 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001967 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001968 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001969
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001970 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001971
Fariborz Jahanian11671902012-02-07 17:11:38 +00001972 return 0;
1973}
1974
1975void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1976{
1977 // Perform a bottom up traversal of all children.
1978 for (Stmt::child_range CI = S->children(); CI; ++CI)
1979 if (*CI)
1980 WarnAboutReturnGotoStmts(*CI);
1981
1982 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1983 Diags.Report(Context->getFullLoc(S->getLocStart()),
1984 TryFinallyContainsReturnDiag);
1985 }
1986 return;
1987}
1988
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001989Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1990 SourceLocation startLoc = S->getAtLoc();
1991 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001992 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1993 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001994
1995 return 0;
1996}
1997
Fariborz Jahanian11671902012-02-07 17:11:38 +00001998Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001999 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002000 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002001 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002002 SourceLocation TryLocation = S->getAtTryLoc();
2003 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002004
2005 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002006 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002007 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002008 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002009 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002010 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002011 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002012 // Get the start location and compute the semi location.
2013 SourceLocation startLoc = S->getLocStart();
2014 const char *startBuf = SM->getCharacterData(startLoc);
2015
2016 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002017 if (finalStmt)
2018 ReplaceText(startLoc, 1, buf);
2019 else
2020 // @try -> try
2021 ReplaceText(startLoc, 1, "");
2022
Fariborz Jahanian11671902012-02-07 17:11:38 +00002023 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2024 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002025 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002026
Fariborz Jahanian11671902012-02-07 17:11:38 +00002027 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002028 bool AtRemoved = false;
2029 if (catchDecl) {
2030 QualType t = catchDecl->getType();
2031 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2032 // Should be a pointer to a class.
2033 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2034 if (IDecl) {
2035 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002036 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2037
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002038 startBuf = SM->getCharacterData(startLoc);
2039 assert((*startBuf == '@') && "bogus @catch location");
2040 SourceLocation rParenLoc = Catch->getRParenLoc();
2041 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2042
2043 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002044 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002045 Result += " *_"; Result += catchDecl->getNameAsString();
2046 Result += ")";
2047 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2048 // Foo *e = (Foo *)_e;
2049 Result.clear();
2050 Result = "{ ";
2051 Result += IDecl->getNameAsString();
2052 Result += " *"; Result += catchDecl->getNameAsString();
2053 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2054 Result += "_"; Result += catchDecl->getNameAsString();
2055
2056 Result += "; ";
2057 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2058 ReplaceText(lBraceLoc, 1, Result);
2059 AtRemoved = true;
2060 }
2061 }
2062 }
2063 if (!AtRemoved)
2064 // @catch -> catch
2065 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002066
Fariborz Jahanian11671902012-02-07 17:11:38 +00002067 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002068 if (finalStmt) {
2069 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002070 SourceLocation FinallyLoc = finalStmt->getLocStart();
2071
2072 if (noCatch) {
2073 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2074 buf += "catch (id e) {_rethrow = e;}\n";
2075 }
2076 else {
2077 buf += "}\n";
2078 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2079 buf += "catch (id e) {_rethrow = e;}\n";
2080 }
2081
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002082 SourceLocation startFinalLoc = finalStmt->getLocStart();
2083 ReplaceText(startFinalLoc, 8, buf);
2084 Stmt *body = finalStmt->getFinallyBody();
2085 SourceLocation startFinalBodyLoc = body->getLocStart();
2086 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002087 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002088 ReplaceText(startFinalBodyLoc, 1, buf);
2089
2090 SourceLocation endFinalBodyLoc = body->getLocEnd();
2091 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002092 // Now check for any return/continue/go statements within the @try.
2093 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002094 }
2095
Fariborz Jahanian11671902012-02-07 17:11:38 +00002096 return 0;
2097}
2098
2099// This can't be done with ReplaceStmt(S, ThrowExpr), since
2100// the throw expression is typically a message expression that's already
2101// been rewritten! (which implies the SourceLocation's are invalid).
2102Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2103 // Get the start location and compute the semi location.
2104 SourceLocation startLoc = S->getLocStart();
2105 const char *startBuf = SM->getCharacterData(startLoc);
2106
2107 assert((*startBuf == '@') && "bogus @throw location");
2108
2109 std::string buf;
2110 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2111 if (S->getThrowExpr())
2112 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002113 else
2114 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002115
2116 // handle "@ throw" correctly.
2117 const char *wBuf = strchr(startBuf, 'w');
2118 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2119 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2120
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002121 SourceLocation endLoc = S->getLocEnd();
2122 const char *endBuf = SM->getCharacterData(endLoc);
2123 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002124 assert((*semiBuf == ';') && "@throw: can't find ';'");
2125 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002126 if (S->getThrowExpr())
2127 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002128 return 0;
2129}
2130
2131Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2132 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002133 std::string StrEncoding;
2134 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002135 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002136 ReplaceStmt(Exp, Replacement);
2137
2138 // Replace this subexpr in the parent.
2139 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2140 return Replacement;
2141}
2142
2143Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2144 if (!SelGetUidFunctionDecl)
2145 SynthSelGetUidFunctionDecl();
2146 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2147 // Create a call to sel_registerName("selName").
2148 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002149 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002150 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2151 &SelExprs[0], SelExprs.size());
2152 ReplaceStmt(Exp, SelExp);
2153 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2154 return SelExp;
2155}
2156
2157CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2158 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2159 SourceLocation EndLoc) {
2160 // Get the type, we will need to reference it in a couple spots.
2161 QualType msgSendType = FD->getType();
2162
2163 // Create a reference to the objc_msgSend() declaration.
2164 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002165 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002166
2167 // Now, we cast the reference to a pointer to the objc_msgSend type.
2168 QualType pToFunc = Context->getPointerType(msgSendType);
2169 ImplicitCastExpr *ICE =
2170 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2171 DRE, 0, VK_RValue);
2172
2173 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2174
2175 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002176 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002177 FT->getCallResultType(*Context),
2178 VK_RValue, EndLoc);
2179 return Exp;
2180}
2181
2182static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2183 const char *&startRef, const char *&endRef) {
2184 while (startBuf < endBuf) {
2185 if (*startBuf == '<')
2186 startRef = startBuf; // mark the start.
2187 if (*startBuf == '>') {
2188 if (startRef && *startRef == '<') {
2189 endRef = startBuf; // mark the end.
2190 return true;
2191 }
2192 return false;
2193 }
2194 startBuf++;
2195 }
2196 return false;
2197}
2198
2199static void scanToNextArgument(const char *&argRef) {
2200 int angle = 0;
2201 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2202 if (*argRef == '<')
2203 angle++;
2204 else if (*argRef == '>')
2205 angle--;
2206 argRef++;
2207 }
2208 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2209}
2210
2211bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2212 if (T->isObjCQualifiedIdType())
2213 return true;
2214 if (const PointerType *PT = T->getAs<PointerType>()) {
2215 if (PT->getPointeeType()->isObjCQualifiedIdType())
2216 return true;
2217 }
2218 if (T->isObjCObjectPointerType()) {
2219 T = T->getPointeeType();
2220 return T->isObjCQualifiedInterfaceType();
2221 }
2222 if (T->isArrayType()) {
2223 QualType ElemTy = Context->getBaseElementType(T);
2224 return needToScanForQualifiers(ElemTy);
2225 }
2226 return false;
2227}
2228
2229void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2230 QualType Type = E->getType();
2231 if (needToScanForQualifiers(Type)) {
2232 SourceLocation Loc, EndLoc;
2233
2234 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2235 Loc = ECE->getLParenLoc();
2236 EndLoc = ECE->getRParenLoc();
2237 } else {
2238 Loc = E->getLocStart();
2239 EndLoc = E->getLocEnd();
2240 }
2241 // This will defend against trying to rewrite synthesized expressions.
2242 if (Loc.isInvalid() || EndLoc.isInvalid())
2243 return;
2244
2245 const char *startBuf = SM->getCharacterData(Loc);
2246 const char *endBuf = SM->getCharacterData(EndLoc);
2247 const char *startRef = 0, *endRef = 0;
2248 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2249 // Get the locations of the startRef, endRef.
2250 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2251 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2252 // Comment out the protocol references.
2253 InsertText(LessLoc, "/*");
2254 InsertText(GreaterLoc, "*/");
2255 }
2256 }
2257}
2258
2259void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2260 SourceLocation Loc;
2261 QualType Type;
2262 const FunctionProtoType *proto = 0;
2263 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2264 Loc = VD->getLocation();
2265 Type = VD->getType();
2266 }
2267 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2268 Loc = FD->getLocation();
2269 // Check for ObjC 'id' and class types that have been adorned with protocol
2270 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2271 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2272 assert(funcType && "missing function type");
2273 proto = dyn_cast<FunctionProtoType>(funcType);
2274 if (!proto)
2275 return;
Alp Toker314cc812014-01-25 16:55:45 +00002276 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002277 }
2278 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2279 Loc = FD->getLocation();
2280 Type = FD->getType();
2281 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002282 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2283 Loc = TD->getLocation();
2284 Type = TD->getUnderlyingType();
2285 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002286 else
2287 return;
2288
2289 if (needToScanForQualifiers(Type)) {
2290 // Since types are unique, we need to scan the buffer.
2291
2292 const char *endBuf = SM->getCharacterData(Loc);
2293 const char *startBuf = endBuf;
2294 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2295 startBuf--; // scan backward (from the decl location) for return type.
2296 const char *startRef = 0, *endRef = 0;
2297 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2298 // Get the locations of the startRef, endRef.
2299 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2300 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2301 // Comment out the protocol references.
2302 InsertText(LessLoc, "/*");
2303 InsertText(GreaterLoc, "*/");
2304 }
2305 }
2306 if (!proto)
2307 return; // most likely, was a variable
2308 // Now check arguments.
2309 const char *startBuf = SM->getCharacterData(Loc);
2310 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002311 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2312 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002313 // Since types are unique, we need to scan the buffer.
2314
2315 const char *endBuf = startBuf;
2316 // scan forward (from the decl location) for argument types.
2317 scanToNextArgument(endBuf);
2318 const char *startRef = 0, *endRef = 0;
2319 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2320 // Get the locations of the startRef, endRef.
2321 SourceLocation LessLoc =
2322 Loc.getLocWithOffset(startRef-startFuncBuf);
2323 SourceLocation GreaterLoc =
2324 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2325 // Comment out the protocol references.
2326 InsertText(LessLoc, "/*");
2327 InsertText(GreaterLoc, "*/");
2328 }
2329 startBuf = ++endBuf;
2330 }
2331 else {
2332 // If the function name is derived from a macro expansion, then the
2333 // argument buffer will not follow the name. Need to speak with Chris.
2334 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2335 startBuf++; // scan forward (from the decl location) for argument types.
2336 startBuf++;
2337 }
2338 }
2339}
2340
2341void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2342 QualType QT = ND->getType();
2343 const Type* TypePtr = QT->getAs<Type>();
2344 if (!isa<TypeOfExprType>(TypePtr))
2345 return;
2346 while (isa<TypeOfExprType>(TypePtr)) {
2347 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2348 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2349 TypePtr = QT->getAs<Type>();
2350 }
2351 // FIXME. This will not work for multiple declarators; as in:
2352 // __typeof__(a) b,c,d;
2353 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2354 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2355 const char *startBuf = SM->getCharacterData(DeclLoc);
2356 if (ND->getInit()) {
2357 std::string Name(ND->getNameAsString());
2358 TypeAsString += " " + Name + " = ";
2359 Expr *E = ND->getInit();
2360 SourceLocation startLoc;
2361 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2362 startLoc = ECE->getLParenLoc();
2363 else
2364 startLoc = E->getLocStart();
2365 startLoc = SM->getExpansionLoc(startLoc);
2366 const char *endBuf = SM->getCharacterData(startLoc);
2367 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2368 }
2369 else {
2370 SourceLocation X = ND->getLocEnd();
2371 X = SM->getExpansionLoc(X);
2372 const char *endBuf = SM->getCharacterData(X);
2373 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2374 }
2375}
2376
2377// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2378void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2379 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2380 SmallVector<QualType, 16> ArgTys;
2381 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2382 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002383 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002384 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002385 SourceLocation(),
2386 SourceLocation(),
2387 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002388 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002389}
2390
2391void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2392 // declared in <objc/objc.h>
2393 if (FD->getIdentifier() &&
2394 FD->getName() == "sel_registerName") {
2395 SelGetUidFunctionDecl = FD;
2396 return;
2397 }
2398 RewriteObjCQualifiedInterfaceTypes(FD);
2399}
2400
2401void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2402 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2403 const char *argPtr = TypeString.c_str();
2404 if (!strchr(argPtr, '^')) {
2405 Str += TypeString;
2406 return;
2407 }
2408 while (*argPtr) {
2409 Str += (*argPtr == '^' ? '*' : *argPtr);
2410 argPtr++;
2411 }
2412}
2413
2414// FIXME. Consolidate this routine with RewriteBlockPointerType.
2415void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2416 ValueDecl *VD) {
2417 QualType Type = VD->getType();
2418 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2419 const char *argPtr = TypeString.c_str();
2420 int paren = 0;
2421 while (*argPtr) {
2422 switch (*argPtr) {
2423 case '(':
2424 Str += *argPtr;
2425 paren++;
2426 break;
2427 case ')':
2428 Str += *argPtr;
2429 paren--;
2430 break;
2431 case '^':
2432 Str += '*';
2433 if (paren == 1)
2434 Str += VD->getNameAsString();
2435 break;
2436 default:
2437 Str += *argPtr;
2438 break;
2439 }
2440 argPtr++;
2441 }
2442}
2443
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002444void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2445 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2446 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2447 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2448 if (!proto)
2449 return;
Alp Toker314cc812014-01-25 16:55:45 +00002450 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002451 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2452 FdStr += " ";
2453 FdStr += FD->getName();
2454 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002455 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002456 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002457 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002458 RewriteBlockPointerType(FdStr, ArgType);
2459 if (i+1 < numArgs)
2460 FdStr += ", ";
2461 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002462 if (FD->isVariadic()) {
2463 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2464 }
2465 else
2466 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002467 InsertText(FunLocStart, FdStr);
2468}
2469
Benjamin Kramer60509af2013-09-09 14:48:42 +00002470// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2471void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2472 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002473 return;
2474 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2475 SmallVector<QualType, 16> ArgTys;
2476 QualType argT = Context->getObjCIdType();
2477 assert(!argT.isNull() && "Can't find 'id' type");
2478 ArgTys.push_back(argT);
2479 ArgTys.push_back(argT);
2480 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002481 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002482 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002483 SourceLocation(),
2484 SourceLocation(),
2485 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002486 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002487}
2488
2489// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2490void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2491 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2492 SmallVector<QualType, 16> ArgTys;
2493 QualType argT = Context->getObjCIdType();
2494 assert(!argT.isNull() && "Can't find 'id' type");
2495 ArgTys.push_back(argT);
2496 argT = Context->getObjCSelType();
2497 assert(!argT.isNull() && "Can't find 'SEL' type");
2498 ArgTys.push_back(argT);
2499 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002500 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002501 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002502 SourceLocation(),
2503 SourceLocation(),
2504 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002505 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002506}
2507
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002508// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002509void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2510 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002511 SmallVector<QualType, 2> ArgTys;
2512 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002514 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002515 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002516 SourceLocation(),
2517 SourceLocation(),
2518 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002519 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002520}
2521
2522// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2523void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2524 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2525 SmallVector<QualType, 16> ArgTys;
2526 QualType argT = Context->getObjCIdType();
2527 assert(!argT.isNull() && "Can't find 'id' type");
2528 ArgTys.push_back(argT);
2529 argT = Context->getObjCSelType();
2530 assert(!argT.isNull() && "Can't find 'SEL' type");
2531 ArgTys.push_back(argT);
2532 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002533 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002534 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002535 SourceLocation(),
2536 SourceLocation(),
2537 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002538 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002539}
2540
2541// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002542// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002543void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2544 IdentifierInfo *msgSendIdent =
2545 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002546 SmallVector<QualType, 2> ArgTys;
2547 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002548 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002549 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002550 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2551 SourceLocation(),
2552 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002553 msgSendIdent,
2554 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002555 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002556}
2557
2558// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2559void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2560 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2561 SmallVector<QualType, 16> ArgTys;
2562 QualType argT = Context->getObjCIdType();
2563 assert(!argT.isNull() && "Can't find 'id' type");
2564 ArgTys.push_back(argT);
2565 argT = Context->getObjCSelType();
2566 assert(!argT.isNull() && "Can't find 'SEL' type");
2567 ArgTys.push_back(argT);
2568 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002569 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002570 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002571 SourceLocation(),
2572 SourceLocation(),
2573 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002574 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002575}
2576
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002577// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002578void RewriteModernObjC::SynthGetClassFunctionDecl() {
2579 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2580 SmallVector<QualType, 16> ArgTys;
2581 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002582 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002583 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002584 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002585 SourceLocation(),
2586 SourceLocation(),
2587 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002588 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002589}
2590
2591// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2592void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2593 IdentifierInfo *getSuperClassIdent =
2594 &Context->Idents.get("class_getSuperclass");
2595 SmallVector<QualType, 16> ArgTys;
2596 ArgTys.push_back(Context->getObjCClassType());
2597 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002598 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002599 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2600 SourceLocation(),
2601 SourceLocation(),
2602 getSuperClassIdent,
2603 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002604 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002605}
2606
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002607// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002608void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2609 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2610 SmallVector<QualType, 16> ArgTys;
2611 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002612 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002613 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002614 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002615 SourceLocation(),
2616 SourceLocation(),
2617 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002618 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002619}
2620
2621Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2622 QualType strType = getConstantStringStructType();
2623
2624 std::string S = "__NSConstantStringImpl_";
2625
2626 std::string tmpName = InFileName;
2627 unsigned i;
2628 for (i=0; i < tmpName.length(); i++) {
2629 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002630 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002631 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002632 tmpName[i] = '_';
2633 }
2634 S += tmpName;
2635 S += "_";
2636 S += utostr(NumObjCStringLiterals++);
2637
2638 Preamble += "static __NSConstantStringImpl " + S;
2639 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2640 Preamble += "0x000007c8,"; // utf8_str
2641 // The pretty printer for StringLiteral handles escape characters properly.
2642 std::string prettyBufS;
2643 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002644 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002645 Preamble += prettyBuf.str();
2646 Preamble += ",";
2647 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2648
2649 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2650 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002651 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002652 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002653 SourceLocation());
2654 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2655 Context->getPointerType(DRE->getType()),
2656 VK_RValue, OK_Ordinary,
2657 SourceLocation());
2658 // cast to NSConstantString *
2659 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2660 CK_CPointerToObjCPointerCast, Unop);
2661 ReplaceStmt(Exp, cast);
2662 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2663 return cast;
2664}
2665
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002666Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2667 unsigned IntSize =
2668 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2669
2670 Expr *FlagExp = IntegerLiteral::Create(*Context,
2671 llvm::APInt(IntSize, Exp->getValue()),
2672 Context->IntTy, Exp->getLocation());
2673 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2674 CK_BitCast, FlagExp);
2675 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2676 cast);
2677 ReplaceStmt(Exp, PE);
2678 return PE;
2679}
2680
Patrick Beard0caa3942012-04-19 00:25:12 +00002681Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002682 // synthesize declaration of helper functions needed in this routine.
2683 if (!SelGetUidFunctionDecl)
2684 SynthSelGetUidFunctionDecl();
2685 // use objc_msgSend() for all.
2686 if (!MsgSendFunctionDecl)
2687 SynthMsgSendFunctionDecl();
2688 if (!GetClassFunctionDecl)
2689 SynthGetClassFunctionDecl();
2690
2691 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2692 SourceLocation StartLoc = Exp->getLocStart();
2693 SourceLocation EndLoc = Exp->getLocEnd();
2694
2695 // Synthesize a call to objc_msgSend().
2696 SmallVector<Expr*, 4> MsgExprs;
2697 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002698
Patrick Beard0caa3942012-04-19 00:25:12 +00002699 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2700 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2701 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002702
Patrick Beard0caa3942012-04-19 00:25:12 +00002703 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002704 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002705 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;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002714 SelExprs.push_back(
2715 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002716 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2717 &SelExprs[0], SelExprs.size(),
2718 StartLoc, EndLoc);
2719 MsgExprs.push_back(SelExp);
2720
Patrick Beard0caa3942012-04-19 00:25:12 +00002721 // User provided sub-expression is the 3rd, and last, argument.
2722 Expr *subExpr = Exp->getSubExpr();
2723 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002724 QualType type = ICE->getType();
2725 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2726 CastKind CK = CK_BitCast;
2727 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2728 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002729 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002730 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002731 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002732
2733 SmallVector<QualType, 4> ArgTypes;
2734 ArgTypes.push_back(Context->getObjCIdType());
2735 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002736 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2737 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002738 ArgTypes.push_back((*PI)->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002739
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002740 QualType returnType = Exp->getType();
2741 // Get the type, we will need to reference it in a couple spots.
2742 QualType msgSendType = MsgSendFlavor->getType();
2743
2744 // Create a reference to the objc_msgSend() declaration.
2745 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2746 VK_LValue, SourceLocation());
2747
2748 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002749 Context->getPointerType(Context->VoidTy),
2750 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002751
2752 // Now do the "normal" pointer to function cast.
2753 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002754 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002755 castType = Context->getPointerType(castType);
2756 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2757 cast);
2758
2759 // Don't forget the parens to enforce the proper binding.
2760 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2761
2762 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002763 CallExpr *CE = new (Context)
2764 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002765 ReplaceStmt(Exp, CE);
2766 return CE;
2767}
2768
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002769Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2770 // synthesize declaration of helper functions needed in this routine.
2771 if (!SelGetUidFunctionDecl)
2772 SynthSelGetUidFunctionDecl();
2773 // use objc_msgSend() for all.
2774 if (!MsgSendFunctionDecl)
2775 SynthMsgSendFunctionDecl();
2776 if (!GetClassFunctionDecl)
2777 SynthGetClassFunctionDecl();
2778
2779 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2780 SourceLocation StartLoc = Exp->getLocStart();
2781 SourceLocation EndLoc = Exp->getLocEnd();
2782
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002783 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002784 QualType IntQT = Context->IntTy;
2785 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002786 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002787 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002788 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2789 DeclRefExpr *NSArrayDRE =
2790 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2791 SourceLocation());
2792
2793 SmallVector<Expr*, 16> InitExprs;
2794 unsigned NumElements = Exp->getNumElements();
2795 unsigned UnsignedIntSize =
2796 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2797 Expr *count = IntegerLiteral::Create(*Context,
2798 llvm::APInt(UnsignedIntSize, NumElements),
2799 Context->UnsignedIntTy, SourceLocation());
2800 InitExprs.push_back(count);
2801 for (unsigned i = 0; i < NumElements; i++)
2802 InitExprs.push_back(Exp->getElement(i));
2803 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002804 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002805 NSArrayFType, VK_LValue, SourceLocation());
2806
2807 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2808 SourceLocation(),
2809 &Context->Idents.get("arr"),
2810 Context->getPointerType(Context->VoidPtrTy), 0,
2811 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002812 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002813 MemberExpr *ArrayLiteralME =
2814 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2815 SourceLocation(),
2816 ARRFD->getType(), VK_LValue,
2817 OK_Ordinary);
2818 QualType ConstIdT = Context->getObjCIdType().withConst();
2819 CStyleCastExpr * ArrayLiteralObjects =
2820 NoTypeInfoCStyleCastExpr(Context,
2821 Context->getPointerType(ConstIdT),
2822 CK_BitCast,
2823 ArrayLiteralME);
2824
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002825 // Synthesize a call to objc_msgSend().
2826 SmallVector<Expr*, 32> MsgExprs;
2827 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002828 QualType expType = Exp->getType();
2829
2830 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2831 ObjCInterfaceDecl *Class =
2832 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2833
2834 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002835 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002836 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2837 &ClsExprs[0],
2838 ClsExprs.size(),
2839 StartLoc, EndLoc);
2840 MsgExprs.push_back(Cls);
2841
2842 // Create a call to sel_registerName("arrayWithObjects:count:").
2843 // it will be the 2nd argument.
2844 SmallVector<Expr*, 4> SelExprs;
2845 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002846 SelExprs.push_back(
2847 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002848 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2849 &SelExprs[0], SelExprs.size(),
2850 StartLoc, EndLoc);
2851 MsgExprs.push_back(SelExp);
2852
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002853 // (const id [])objects
2854 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002855
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002856 // (NSUInteger)cnt
2857 Expr *cnt = IntegerLiteral::Create(*Context,
2858 llvm::APInt(UnsignedIntSize, NumElements),
2859 Context->UnsignedIntTy, SourceLocation());
2860 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002861
2862
2863 SmallVector<QualType, 4> ArgTypes;
2864 ArgTypes.push_back(Context->getObjCIdType());
2865 ArgTypes.push_back(Context->getObjCSelType());
2866 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2867 E = ArrayMethod->param_end(); PI != E; ++PI)
2868 ArgTypes.push_back((*PI)->getType());
2869
2870 QualType returnType = Exp->getType();
2871 // Get the type, we will need to reference it in a couple spots.
2872 QualType msgSendType = MsgSendFlavor->getType();
2873
2874 // Create a reference to the objc_msgSend() declaration.
2875 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2876 VK_LValue, SourceLocation());
2877
2878 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2879 Context->getPointerType(Context->VoidTy),
2880 CK_BitCast, DRE);
2881
2882 // Now do the "normal" pointer to function cast.
2883 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002884 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002885 castType = Context->getPointerType(castType);
2886 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2887 cast);
2888
2889 // Don't forget the parens to enforce the proper binding.
2890 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2891
2892 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002893 CallExpr *CE = new (Context)
2894 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002895 ReplaceStmt(Exp, CE);
2896 return CE;
2897}
2898
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002899Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2900 // synthesize declaration of helper functions needed in this routine.
2901 if (!SelGetUidFunctionDecl)
2902 SynthSelGetUidFunctionDecl();
2903 // use objc_msgSend() for all.
2904 if (!MsgSendFunctionDecl)
2905 SynthMsgSendFunctionDecl();
2906 if (!GetClassFunctionDecl)
2907 SynthGetClassFunctionDecl();
2908
2909 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2910 SourceLocation StartLoc = Exp->getLocStart();
2911 SourceLocation EndLoc = Exp->getLocEnd();
2912
2913 // Build the expression: __NSContainer_literal(int, ...).arr
2914 QualType IntQT = Context->IntTy;
2915 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002916 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002917 std::string NSDictFName("__NSContainer_literal");
2918 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2919 DeclRefExpr *NSDictDRE =
2920 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2921 SourceLocation());
2922
2923 SmallVector<Expr*, 16> KeyExprs;
2924 SmallVector<Expr*, 16> ValueExprs;
2925
2926 unsigned NumElements = Exp->getNumElements();
2927 unsigned UnsignedIntSize =
2928 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2929 Expr *count = IntegerLiteral::Create(*Context,
2930 llvm::APInt(UnsignedIntSize, NumElements),
2931 Context->UnsignedIntTy, SourceLocation());
2932 KeyExprs.push_back(count);
2933 ValueExprs.push_back(count);
2934 for (unsigned i = 0; i < NumElements; i++) {
2935 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2936 KeyExprs.push_back(Element.Key);
2937 ValueExprs.push_back(Element.Value);
2938 }
2939
2940 // (const id [])objects
2941 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002942 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002943 NSDictFType, VK_LValue, SourceLocation());
2944
2945 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2946 SourceLocation(),
2947 &Context->Idents.get("arr"),
2948 Context->getPointerType(Context->VoidPtrTy), 0,
2949 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002950 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002951 MemberExpr *DictLiteralValueME =
2952 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2953 SourceLocation(),
2954 ARRFD->getType(), VK_LValue,
2955 OK_Ordinary);
2956 QualType ConstIdT = Context->getObjCIdType().withConst();
2957 CStyleCastExpr * DictValueObjects =
2958 NoTypeInfoCStyleCastExpr(Context,
2959 Context->getPointerType(ConstIdT),
2960 CK_BitCast,
2961 DictLiteralValueME);
2962 // (const id <NSCopying> [])keys
2963 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002964 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002965 NSDictFType, VK_LValue, SourceLocation());
2966
2967 MemberExpr *DictLiteralKeyME =
2968 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2969 SourceLocation(),
2970 ARRFD->getType(), VK_LValue,
2971 OK_Ordinary);
2972
2973 CStyleCastExpr * DictKeyObjects =
2974 NoTypeInfoCStyleCastExpr(Context,
2975 Context->getPointerType(ConstIdT),
2976 CK_BitCast,
2977 DictLiteralKeyME);
2978
2979
2980
2981 // Synthesize a call to objc_msgSend().
2982 SmallVector<Expr*, 32> MsgExprs;
2983 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002984 QualType expType = Exp->getType();
2985
2986 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2987 ObjCInterfaceDecl *Class =
2988 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2989
2990 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002991 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002992 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2993 &ClsExprs[0],
2994 ClsExprs.size(),
2995 StartLoc, EndLoc);
2996 MsgExprs.push_back(Cls);
2997
2998 // Create a call to sel_registerName("arrayWithObjects:count:").
2999 // it will be the 2nd argument.
3000 SmallVector<Expr*, 4> SelExprs;
3001 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003002 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003003 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3004 &SelExprs[0], SelExprs.size(),
3005 StartLoc, EndLoc);
3006 MsgExprs.push_back(SelExp);
3007
3008 // (const id [])objects
3009 MsgExprs.push_back(DictValueObjects);
3010
3011 // (const id <NSCopying> [])keys
3012 MsgExprs.push_back(DictKeyObjects);
3013
3014 // (NSUInteger)cnt
3015 Expr *cnt = IntegerLiteral::Create(*Context,
3016 llvm::APInt(UnsignedIntSize, NumElements),
3017 Context->UnsignedIntTy, SourceLocation());
3018 MsgExprs.push_back(cnt);
3019
3020
3021 SmallVector<QualType, 8> ArgTypes;
3022 ArgTypes.push_back(Context->getObjCIdType());
3023 ArgTypes.push_back(Context->getObjCSelType());
3024 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3025 E = DictMethod->param_end(); PI != E; ++PI) {
3026 QualType T = (*PI)->getType();
3027 if (const PointerType* PT = T->getAs<PointerType>()) {
3028 QualType PointeeTy = PT->getPointeeType();
3029 convertToUnqualifiedObjCType(PointeeTy);
3030 T = Context->getPointerType(PointeeTy);
3031 }
3032 ArgTypes.push_back(T);
3033 }
3034
3035 QualType returnType = Exp->getType();
3036 // Get the type, we will need to reference it in a couple spots.
3037 QualType msgSendType = MsgSendFlavor->getType();
3038
3039 // Create a reference to the objc_msgSend() declaration.
3040 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3041 VK_LValue, SourceLocation());
3042
3043 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3044 Context->getPointerType(Context->VoidTy),
3045 CK_BitCast, DRE);
3046
3047 // Now do the "normal" pointer to function cast.
3048 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003049 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003050 castType = Context->getPointerType(castType);
3051 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3052 cast);
3053
3054 // Don't forget the parens to enforce the proper binding.
3055 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3056
3057 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003058 CallExpr *CE = new (Context)
3059 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003060 ReplaceStmt(Exp, CE);
3061 return CE;
3062}
3063
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003064// struct __rw_objc_super {
3065// struct objc_object *object; struct objc_object *superClass;
3066// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003067QualType RewriteModernObjC::getSuperStructType() {
3068 if (!SuperStructDecl) {
3069 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3070 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003071 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003072 QualType FieldTypes[2];
3073
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003074 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003075 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003076 // struct objc_object *superClass;
3077 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003078
3079 // Create fields
3080 for (unsigned i = 0; i < 2; ++i) {
3081 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3082 SourceLocation(),
3083 SourceLocation(), 0,
3084 FieldTypes[i], 0,
3085 /*BitWidth=*/0,
3086 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003087 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003088 }
3089
3090 SuperStructDecl->completeDefinition();
3091 }
3092 return Context->getTagDeclType(SuperStructDecl);
3093}
3094
3095QualType RewriteModernObjC::getConstantStringStructType() {
3096 if (!ConstantStringDecl) {
3097 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3098 SourceLocation(), SourceLocation(),
3099 &Context->Idents.get("__NSConstantStringImpl"));
3100 QualType FieldTypes[4];
3101
3102 // struct objc_object *receiver;
3103 FieldTypes[0] = Context->getObjCIdType();
3104 // int flags;
3105 FieldTypes[1] = Context->IntTy;
3106 // char *str;
3107 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3108 // long length;
3109 FieldTypes[3] = Context->LongTy;
3110
3111 // Create fields
3112 for (unsigned i = 0; i < 4; ++i) {
3113 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3114 ConstantStringDecl,
3115 SourceLocation(),
3116 SourceLocation(), 0,
3117 FieldTypes[i], 0,
3118 /*BitWidth=*/0,
3119 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003120 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003121 }
3122
3123 ConstantStringDecl->completeDefinition();
3124 }
3125 return Context->getTagDeclType(ConstantStringDecl);
3126}
3127
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003128/// getFunctionSourceLocation - returns start location of a function
3129/// definition. Complication arises when function has declared as
3130/// extern "C" or extern "C" {...}
3131static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3132 FunctionDecl *FD) {
3133 if (FD->isExternC() && !FD->isMain()) {
3134 const DeclContext *DC = FD->getDeclContext();
3135 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3136 // if it is extern "C" {...}, return function decl's own location.
3137 if (!LSD->getRBraceLoc().isValid())
3138 return LSD->getExternLoc();
3139 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003140 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003141 R.RewriteBlockLiteralFunctionDecl(FD);
3142 return FD->getTypeSpecStartLoc();
3143}
3144
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003145void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3146
3147 SourceLocation Location = D->getLocation();
3148
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003149 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003150 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003151 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3152 LineString += utostr(PLoc.getLine());
3153 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003154 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003155 if (isa<ObjCMethodDecl>(D))
3156 LineString += "\"";
3157 else LineString += "\"\n";
3158
3159 Location = D->getLocStart();
3160 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3161 if (FD->isExternC() && !FD->isMain()) {
3162 const DeclContext *DC = FD->getDeclContext();
3163 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3164 // if it is extern "C" {...}, return function decl's own location.
3165 if (!LSD->getRBraceLoc().isValid())
3166 Location = LSD->getExternLoc();
3167 }
3168 }
3169 InsertText(Location, LineString);
3170 }
3171}
3172
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003173/// SynthMsgSendStretCallExpr - This routine translates message expression
3174/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3175/// nil check on receiver must be performed before calling objc_msgSend_stret.
3176/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3177/// msgSendType - function type of objc_msgSend_stret(...)
3178/// returnType - Result type of the method being synthesized.
3179/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3180/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3181/// starting with receiver.
3182/// Method - Method being rewritten.
3183Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003184 QualType returnType,
3185 SmallVectorImpl<QualType> &ArgTypes,
3186 SmallVectorImpl<Expr*> &MsgExprs,
3187 ObjCMethodDecl *Method) {
3188 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003189 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3190 Method ? Method->isVariadic()
3191 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003192 castType = Context->getPointerType(castType);
3193
3194 // build type for containing the objc_msgSend_stret object.
3195 static unsigned stretCount=0;
3196 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003197 std::string str =
3198 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003199 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003200 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003201 str += " {\n\t";
3202 str += name;
3203 str += "(id receiver, SEL sel";
3204 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003205 std::string ArgName = "arg"; ArgName += utostr(i);
3206 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3207 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003208 }
3209 // could be vararg.
3210 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003211 std::string ArgName = "arg"; ArgName += utostr(i);
3212 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3213 Context->getPrintingPolicy());
3214 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003215 }
3216
3217 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003218 str += "\t unsigned size = sizeof(";
3219 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3220
3221 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3222
3223 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3224 str += ")(void *)objc_msgSend)(receiver, sel";
3225 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3226 str += ", arg"; str += utostr(i);
3227 }
3228 // could be vararg.
3229 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3230 str += ", arg"; str += utostr(i);
3231 }
3232 str+= ");\n";
3233
3234 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003235 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3236 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003237
3238
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003239 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3240 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3241 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3242 str += ", arg"; str += utostr(i);
3243 }
3244 // could be vararg.
3245 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3246 str += ", arg"; str += utostr(i);
3247 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003248 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003249
3250
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003251 str += "\t}\n";
3252 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3253 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003254 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003255 SourceLocation FunLocStart;
3256 if (CurFunctionDef)
3257 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3258 else {
3259 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3260 FunLocStart = CurMethodDef->getLocStart();
3261 }
3262
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003263 InsertText(FunLocStart, str);
3264 ++stretCount;
3265
3266 // AST for __Stretn(receiver, args).s;
3267 IdentifierInfo *ID = &Context->Idents.get(name);
3268 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003269 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003270 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003271 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3272 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003273 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003274 castType, VK_LValue, SourceLocation());
3275
3276 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3277 SourceLocation(),
3278 &Context->Idents.get("s"),
3279 returnType, 0,
3280 /*BitWidth=*/0, /*Mutable=*/true,
3281 ICIS_NoInit);
3282 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3283 FieldD->getType(), VK_LValue,
3284 OK_Ordinary);
3285
3286 return ME;
3287}
3288
Fariborz Jahanian11671902012-02-07 17:11:38 +00003289Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3290 SourceLocation StartLoc,
3291 SourceLocation EndLoc) {
3292 if (!SelGetUidFunctionDecl)
3293 SynthSelGetUidFunctionDecl();
3294 if (!MsgSendFunctionDecl)
3295 SynthMsgSendFunctionDecl();
3296 if (!MsgSendSuperFunctionDecl)
3297 SynthMsgSendSuperFunctionDecl();
3298 if (!MsgSendStretFunctionDecl)
3299 SynthMsgSendStretFunctionDecl();
3300 if (!MsgSendSuperStretFunctionDecl)
3301 SynthMsgSendSuperStretFunctionDecl();
3302 if (!MsgSendFpretFunctionDecl)
3303 SynthMsgSendFpretFunctionDecl();
3304 if (!GetClassFunctionDecl)
3305 SynthGetClassFunctionDecl();
3306 if (!GetSuperClassFunctionDecl)
3307 SynthGetSuperClassFunctionDecl();
3308 if (!GetMetaClassFunctionDecl)
3309 SynthGetMetaClassFunctionDecl();
3310
3311 // default to objc_msgSend().
3312 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3313 // May need to use objc_msgSend_stret() as well.
3314 FunctionDecl *MsgSendStretFlavor = 0;
3315 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003316 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003317 if (resultType->isRecordType())
3318 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3319 else if (resultType->isRealFloatingType())
3320 MsgSendFlavor = MsgSendFpretFunctionDecl;
3321 }
3322
3323 // Synthesize a call to objc_msgSend().
3324 SmallVector<Expr*, 8> MsgExprs;
3325 switch (Exp->getReceiverKind()) {
3326 case ObjCMessageExpr::SuperClass: {
3327 MsgSendFlavor = MsgSendSuperFunctionDecl;
3328 if (MsgSendStretFlavor)
3329 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3330 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3331
3332 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3333
3334 SmallVector<Expr*, 4> InitExprs;
3335
3336 // set the receiver to self, the first argument to all methods.
3337 InitExprs.push_back(
3338 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3339 CK_BitCast,
3340 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003341 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003342 Context->getObjCIdType(),
3343 VK_RValue,
3344 SourceLocation()))
3345 ); // set the 'receiver'.
3346
3347 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3348 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003349 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003350 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003351 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3352 &ClsExprs[0],
3353 ClsExprs.size(),
3354 StartLoc,
3355 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003356 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003357 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003358 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3359 &ClsExprs[0], ClsExprs.size(),
3360 StartLoc, EndLoc);
3361
3362 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3363 // To turn off a warning, type-cast to 'id'
3364 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3365 NoTypeInfoCStyleCastExpr(Context,
3366 Context->getObjCIdType(),
3367 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003368 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003369 QualType superType = getSuperStructType();
3370 Expr *SuperRep;
3371
3372 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003373 SynthSuperConstructorFunctionDecl();
3374 // Simulate a constructor call...
3375 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003376 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003377 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003378 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003379 superType, VK_LValue,
3380 SourceLocation());
3381 // The code for super is a little tricky to prevent collision with
3382 // the structure definition in the header. The rewriter has it's own
3383 // internal definition (__rw_objc_super) that is uses. This is why
3384 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003385 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003386 //
3387 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3388 Context->getPointerType(SuperRep->getType()),
3389 VK_RValue, OK_Ordinary,
3390 SourceLocation());
3391 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3392 Context->getPointerType(superType),
3393 CK_BitCast, SuperRep);
3394 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003395 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003396 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003397 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003398 SourceLocation());
3399 TypeSourceInfo *superTInfo
3400 = Context->getTrivialTypeSourceInfo(superType);
3401 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3402 superType, VK_LValue,
3403 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003404 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003405 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3406 Context->getPointerType(SuperRep->getType()),
3407 VK_RValue, OK_Ordinary,
3408 SourceLocation());
3409 }
3410 MsgExprs.push_back(SuperRep);
3411 break;
3412 }
3413
3414 case ObjCMessageExpr::Class: {
3415 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003416 ObjCInterfaceDecl *Class
3417 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3418 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003419 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003420 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3421 &ClsExprs[0],
3422 ClsExprs.size(),
3423 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003424 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3425 Context->getObjCIdType(),
3426 CK_BitCast, Cls);
3427 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003428 break;
3429 }
3430
3431 case ObjCMessageExpr::SuperInstance:{
3432 MsgSendFlavor = MsgSendSuperFunctionDecl;
3433 if (MsgSendStretFlavor)
3434 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3435 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3436 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3437 SmallVector<Expr*, 4> InitExprs;
3438
3439 InitExprs.push_back(
3440 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3441 CK_BitCast,
3442 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003443 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003444 Context->getObjCIdType(),
3445 VK_RValue, SourceLocation()))
3446 ); // set the 'receiver'.
3447
3448 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3449 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003450 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003451 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003452 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3453 &ClsExprs[0],
3454 ClsExprs.size(),
3455 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003456 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003457 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003458 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3459 &ClsExprs[0], ClsExprs.size(),
3460 StartLoc, EndLoc);
3461
3462 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3463 // To turn off a warning, type-cast to 'id'
3464 InitExprs.push_back(
3465 // set 'super class', using class_getSuperclass().
3466 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3467 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003468 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003469 QualType superType = getSuperStructType();
3470 Expr *SuperRep;
3471
3472 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003473 SynthSuperConstructorFunctionDecl();
3474 // Simulate a constructor call...
3475 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003476 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003477 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003478 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003479 superType, VK_LValue, SourceLocation());
3480 // The code for super is a little tricky to prevent collision with
3481 // the structure definition in the header. The rewriter has it's own
3482 // internal definition (__rw_objc_super) that is uses. This is why
3483 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003484 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003485 //
3486 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3487 Context->getPointerType(SuperRep->getType()),
3488 VK_RValue, OK_Ordinary,
3489 SourceLocation());
3490 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3491 Context->getPointerType(superType),
3492 CK_BitCast, SuperRep);
3493 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003494 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003495 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003496 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003497 SourceLocation());
3498 TypeSourceInfo *superTInfo
3499 = Context->getTrivialTypeSourceInfo(superType);
3500 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3501 superType, VK_RValue, ILE,
3502 false);
3503 }
3504 MsgExprs.push_back(SuperRep);
3505 break;
3506 }
3507
3508 case ObjCMessageExpr::Instance: {
3509 // Remove all type-casts because it may contain objc-style types; e.g.
3510 // Foo<Proto> *.
3511 Expr *recExpr = Exp->getInstanceReceiver();
3512 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3513 recExpr = CE->getSubExpr();
3514 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3515 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3516 ? CK_BlockPointerToObjCPointerCast
3517 : CK_CPointerToObjCPointerCast;
3518
3519 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3520 CK, recExpr);
3521 MsgExprs.push_back(recExpr);
3522 break;
3523 }
3524 }
3525
3526 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3527 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003528 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003529 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3530 &SelExprs[0], SelExprs.size(),
3531 StartLoc,
3532 EndLoc);
3533 MsgExprs.push_back(SelExp);
3534
3535 // Now push any user supplied arguments.
3536 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3537 Expr *userExpr = Exp->getArg(i);
3538 // Make all implicit casts explicit...ICE comes in handy:-)
3539 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3540 // Reuse the ICE type, it is exactly what the doctor ordered.
3541 QualType type = ICE->getType();
3542 if (needToScanForQualifiers(type))
3543 type = Context->getObjCIdType();
3544 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3545 (void)convertBlockPointerToFunctionPointer(type);
3546 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3547 CastKind CK;
3548 if (SubExpr->getType()->isIntegralType(*Context) &&
3549 type->isBooleanType()) {
3550 CK = CK_IntegralToBoolean;
3551 } else if (type->isObjCObjectPointerType()) {
3552 if (SubExpr->getType()->isBlockPointerType()) {
3553 CK = CK_BlockPointerToObjCPointerCast;
3554 } else if (SubExpr->getType()->isPointerType()) {
3555 CK = CK_CPointerToObjCPointerCast;
3556 } else {
3557 CK = CK_BitCast;
3558 }
3559 } else {
3560 CK = CK_BitCast;
3561 }
3562
3563 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3564 }
3565 // Make id<P...> cast into an 'id' cast.
3566 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3567 if (CE->getType()->isObjCQualifiedIdType()) {
3568 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3569 userExpr = CE->getSubExpr();
3570 CastKind CK;
3571 if (userExpr->getType()->isIntegralType(*Context)) {
3572 CK = CK_IntegralToPointer;
3573 } else if (userExpr->getType()->isBlockPointerType()) {
3574 CK = CK_BlockPointerToObjCPointerCast;
3575 } else if (userExpr->getType()->isPointerType()) {
3576 CK = CK_CPointerToObjCPointerCast;
3577 } else {
3578 CK = CK_BitCast;
3579 }
3580 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3581 CK, userExpr);
3582 }
3583 }
3584 MsgExprs.push_back(userExpr);
3585 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3586 // out the argument in the original expression (since we aren't deleting
3587 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3588 //Exp->setArg(i, 0);
3589 }
3590 // Generate the funky cast.
3591 CastExpr *cast;
3592 SmallVector<QualType, 8> ArgTypes;
3593 QualType returnType;
3594
3595 // Push 'id' and 'SEL', the 2 implicit arguments.
3596 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3597 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3598 else
3599 ArgTypes.push_back(Context->getObjCIdType());
3600 ArgTypes.push_back(Context->getObjCSelType());
3601 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3602 // Push any user argument types.
3603 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3604 E = OMD->param_end(); PI != E; ++PI) {
3605 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3606 ? Context->getObjCIdType()
3607 : (*PI)->getType();
3608 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3609 (void)convertBlockPointerToFunctionPointer(t);
3610 ArgTypes.push_back(t);
3611 }
3612 returnType = Exp->getType();
3613 convertToUnqualifiedObjCType(returnType);
3614 (void)convertBlockPointerToFunctionPointer(returnType);
3615 } else {
3616 returnType = Context->getObjCIdType();
3617 }
3618 // Get the type, we will need to reference it in a couple spots.
3619 QualType msgSendType = MsgSendFlavor->getType();
3620
3621 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003622 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003623 VK_LValue, SourceLocation());
3624
3625 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3626 // If we don't do this cast, we get the following bizarre warning/note:
3627 // xx.m:13: warning: function called through a non-compatible type
3628 // xx.m:13: note: if this code is reached, the program will abort
3629 cast = NoTypeInfoCStyleCastExpr(Context,
3630 Context->getPointerType(Context->VoidTy),
3631 CK_BitCast, DRE);
3632
3633 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003634 // If we don't have a method decl, force a variadic cast.
3635 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003636 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003637 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003638 castType = Context->getPointerType(castType);
3639 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3640 cast);
3641
3642 // Don't forget the parens to enforce the proper binding.
3643 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3644
3645 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003646 CallExpr *CE = new (Context)
3647 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003648 Stmt *ReplacingStmt = CE;
3649 if (MsgSendStretFlavor) {
3650 // We have the method which returns a struct/union. Must also generate
3651 // call to objc_msgSend_stret and hang both varieties on a conditional
3652 // expression which dictate which one to envoke depending on size of
3653 // method's return type.
3654
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003655 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3656 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003657 ArgTypes, MsgExprs,
3658 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003659 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003660 }
3661 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3662 return ReplacingStmt;
3663}
3664
3665Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3666 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3667 Exp->getLocEnd());
3668
3669 // Now do the actual rewrite.
3670 ReplaceStmt(Exp, ReplacingStmt);
3671
3672 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3673 return ReplacingStmt;
3674}
3675
3676// typedef struct objc_object Protocol;
3677QualType RewriteModernObjC::getProtocolType() {
3678 if (!ProtocolTypeDecl) {
3679 TypeSourceInfo *TInfo
3680 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3681 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3682 SourceLocation(), SourceLocation(),
3683 &Context->Idents.get("Protocol"),
3684 TInfo);
3685 }
3686 return Context->getTypeDeclType(ProtocolTypeDecl);
3687}
3688
3689/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3690/// a synthesized/forward data reference (to the protocol's metadata).
3691/// The forward references (and metadata) are generated in
3692/// RewriteModernObjC::HandleTranslationUnit().
3693Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003694 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3695 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003696 IdentifierInfo *ID = &Context->Idents.get(Name);
3697 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3698 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003699 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003700 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3701 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003702 CastExpr *castExpr =
3703 NoTypeInfoCStyleCastExpr(
3704 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003705 ReplaceStmt(Exp, castExpr);
3706 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3707 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3708 return castExpr;
3709
3710}
3711
3712bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3713 const char *endBuf) {
3714 while (startBuf < endBuf) {
3715 if (*startBuf == '#') {
3716 // Skip whitespace.
3717 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3718 ;
3719 if (!strncmp(startBuf, "if", strlen("if")) ||
3720 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3721 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3722 !strncmp(startBuf, "define", strlen("define")) ||
3723 !strncmp(startBuf, "undef", strlen("undef")) ||
3724 !strncmp(startBuf, "else", strlen("else")) ||
3725 !strncmp(startBuf, "elif", strlen("elif")) ||
3726 !strncmp(startBuf, "endif", strlen("endif")) ||
3727 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3728 !strncmp(startBuf, "include", strlen("include")) ||
3729 !strncmp(startBuf, "import", strlen("import")) ||
3730 !strncmp(startBuf, "include_next", strlen("include_next")))
3731 return true;
3732 }
3733 startBuf++;
3734 }
3735 return false;
3736}
3737
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003738/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3739/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003740bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003741 TagDecl *Tag,
3742 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003743 if (!IDecl)
3744 return false;
3745 SourceLocation TagLocation;
3746 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3747 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003748 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003749 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003750 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003751 TagLocation = RD->getLocation();
3752 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003753 IDecl->getLocation(), TagLocation);
3754 }
3755 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3756 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3757 return false;
3758 IsNamedDefinition = true;
3759 TagLocation = ED->getLocation();
3760 return Context->getSourceManager().isBeforeInTranslationUnit(
3761 IDecl->getLocation(), TagLocation);
3762
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003763 }
3764 return false;
3765}
3766
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003767/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003768/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003769bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3770 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003771 if (isa<TypedefType>(Type)) {
3772 Result += "\t";
3773 return false;
3774 }
3775
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003776 if (Type->isArrayType()) {
3777 QualType ElemTy = Context->getBaseElementType(Type);
3778 return RewriteObjCFieldDeclType(ElemTy, Result);
3779 }
3780 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003781 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3782 if (RD->isCompleteDefinition()) {
3783 if (RD->isStruct())
3784 Result += "\n\tstruct ";
3785 else if (RD->isUnion())
3786 Result += "\n\tunion ";
3787 else
3788 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003789
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003790 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003791 if (GlobalDefinedTags.count(RD)) {
3792 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003793 Result += " ";
3794 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003795 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003796 Result += " {\n";
3797 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003798 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003799 FieldDecl *FD = *i;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003800 RewriteObjCFieldDecl(FD, Result);
3801 }
3802 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003803 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003804 }
3805 }
3806 else if (Type->isEnumeralType()) {
3807 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3808 if (ED->isCompleteDefinition()) {
3809 Result += "\n\tenum ";
3810 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003811 if (GlobalDefinedTags.count(ED)) {
3812 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003813 Result += " ";
3814 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003815 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003816
3817 Result += " {\n";
3818 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3819 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3820 Result += "\t"; Result += EC->getName(); Result += " = ";
3821 llvm::APSInt Val = EC->getInitVal();
3822 Result += Val.toString(10);
3823 Result += ",\n";
3824 }
3825 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003826 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003827 }
3828 }
3829
3830 Result += "\t";
3831 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003832 return false;
3833}
3834
3835
3836/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3837/// It handles elaborated types, as well as enum types in the process.
3838void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3839 std::string &Result) {
3840 QualType Type = fieldDecl->getType();
3841 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003842
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003843 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3844 if (!EleboratedType)
3845 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003846 Result += Name;
3847 if (fieldDecl->isBitField()) {
3848 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3849 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003850 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003851 const ArrayType *AT = Context->getAsArrayType(Type);
3852 do {
3853 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003854 Result += "[";
3855 llvm::APInt Dim = CAT->getSize();
3856 Result += utostr(Dim.getZExtValue());
3857 Result += "]";
3858 }
Eli Friedman07bab732012-12-13 01:43:21 +00003859 AT = Context->getAsArrayType(AT->getElementType());
3860 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003861 }
3862
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003863 Result += ";\n";
3864}
3865
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003866/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3867/// named aggregate types into the input buffer.
3868void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3869 std::string &Result) {
3870 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003871 if (isa<TypedefType>(Type))
3872 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003873 if (Type->isArrayType())
3874 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003875 ObjCContainerDecl *IDecl =
3876 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003877
3878 TagDecl *TD = 0;
3879 if (Type->isRecordType()) {
3880 TD = Type->getAs<RecordType>()->getDecl();
3881 }
3882 else if (Type->isEnumeralType()) {
3883 TD = Type->getAs<EnumType>()->getDecl();
3884 }
3885
3886 if (TD) {
3887 if (GlobalDefinedTags.count(TD))
3888 return;
3889
3890 bool IsNamedDefinition = false;
3891 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3892 RewriteObjCFieldDeclType(Type, Result);
3893 Result += ";";
3894 }
3895 if (IsNamedDefinition)
3896 GlobalDefinedTags.insert(TD);
3897 }
3898
3899}
3900
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003901unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3902 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3903 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3904 return IvarGroupNumber[IV];
3905 }
3906 unsigned GroupNo = 0;
3907 SmallVector<const ObjCIvarDecl *, 8> IVars;
3908 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3909 IVD; IVD = IVD->getNextIvar())
3910 IVars.push_back(IVD);
3911
3912 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3913 if (IVars[i]->isBitField()) {
3914 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3915 while (i < e && IVars[i]->isBitField())
3916 IvarGroupNumber[IVars[i++]] = GroupNo;
3917 if (i < e)
3918 --i;
3919 }
3920
3921 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3922 return IvarGroupNumber[IV];
3923}
3924
3925QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3926 ObjCIvarDecl *IV,
3927 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3928 std::string StructTagName;
3929 ObjCIvarBitfieldGroupType(IV, StructTagName);
3930 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3931 Context->getTranslationUnitDecl(),
3932 SourceLocation(), SourceLocation(),
3933 &Context->Idents.get(StructTagName));
3934 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3935 ObjCIvarDecl *Ivar = IVars[i];
3936 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3937 &Context->Idents.get(Ivar->getName()),
3938 Ivar->getType(),
3939 0, /*Expr *BW */Ivar->getBitWidth(), false,
3940 ICIS_NoInit));
3941 }
3942 RD->completeDefinition();
3943 return Context->getTagDeclType(RD);
3944}
3945
3946QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3947 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3948 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3949 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3950 if (GroupRecordType.count(tuple))
3951 return GroupRecordType[tuple];
3952
3953 SmallVector<ObjCIvarDecl *, 8> IVars;
3954 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3955 IVD; IVD = IVD->getNextIvar()) {
3956 if (IVD->isBitField())
3957 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3958 else {
3959 if (!IVars.empty()) {
3960 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3961 // Generate the struct type for this group of bitfield ivars.
3962 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3963 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3964 IVars.clear();
3965 }
3966 }
3967 }
3968 if (!IVars.empty()) {
3969 // Do the last one.
3970 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3971 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3972 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3973 }
3974 QualType RetQT = GroupRecordType[tuple];
3975 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3976
3977 return RetQT;
3978}
3979
3980/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3981/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3982void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3983 std::string &Result) {
3984 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3985 Result += CDecl->getName();
3986 Result += "__GRBF_";
3987 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3988 Result += utostr(GroupNo);
3989 return;
3990}
3991
3992/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3993/// Name of the struct would be: classname__T_n where n is the group number for
3994/// this ivar.
3995void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3996 std::string &Result) {
3997 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3998 Result += CDecl->getName();
3999 Result += "__T_";
4000 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4001 Result += utostr(GroupNo);
4002 return;
4003}
4004
4005/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4006/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4007/// this ivar.
4008void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4009 std::string &Result) {
4010 Result += "OBJC_IVAR_$_";
4011 ObjCIvarBitfieldGroupDecl(IV, Result);
4012}
4013
4014#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4015 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4016 ++IX; \
4017 if (IX < ENDIX) \
4018 --IX; \
4019}
4020
Fariborz Jahanian11671902012-02-07 17:11:38 +00004021/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4022/// an objective-c class with ivars.
4023void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4024 std::string &Result) {
4025 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4026 assert(CDecl->getName() != "" &&
4027 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004028 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004029 SmallVector<ObjCIvarDecl *, 8> IVars;
4030 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004031 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004032 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004033
Fariborz Jahanian11671902012-02-07 17:11:38 +00004034 SourceLocation LocStart = CDecl->getLocStart();
4035 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004036
Fariborz Jahanian11671902012-02-07 17:11:38 +00004037 const char *startBuf = SM->getCharacterData(LocStart);
4038 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004039
Fariborz Jahanian11671902012-02-07 17:11:38 +00004040 // If no ivars and no root or if its root, directly or indirectly,
4041 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004042 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004043 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4044 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4045 ReplaceText(LocStart, endBuf-startBuf, Result);
4046 return;
4047 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004048
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004049 // Insert named struct/union definitions inside class to
4050 // outer scope. This follows semantics of locally defined
4051 // struct/unions in objective-c classes.
4052 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4053 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004054
4055 // Insert named structs which are syntheized to group ivar bitfields
4056 // to outer scope as well.
4057 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4058 if (IVars[i]->isBitField()) {
4059 ObjCIvarDecl *IV = IVars[i];
4060 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4061 RewriteObjCFieldDeclType(QT, Result);
4062 Result += ";";
4063 // skip over ivar bitfields in this group.
4064 SKIP_BITFIELDS(i , e, IVars);
4065 }
4066
Fariborz Jahanian11671902012-02-07 17:11:38 +00004067 Result += "\nstruct ";
4068 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004069 Result += "_IMPL {\n";
4070
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004071 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004072 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4073 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4074 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004075 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004076
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004077 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4078 if (IVars[i]->isBitField()) {
4079 ObjCIvarDecl *IV = IVars[i];
4080 Result += "\tstruct ";
4081 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4082 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4083 // skip over ivar bitfields in this group.
4084 SKIP_BITFIELDS(i , e, IVars);
4085 }
4086 else
4087 RewriteObjCFieldDecl(IVars[i], Result);
4088 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004089
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004090 Result += "};\n";
4091 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4092 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004093 // Mark this struct as having been generated.
4094 if (!ObjCSynthesizedStructs.insert(CDecl))
4095 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004096}
4097
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004098/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4099/// have been referenced in an ivar access expression.
4100void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4101 std::string &Result) {
4102 // write out ivar offset symbols which have been referenced in an ivar
4103 // access expression.
4104 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4105 if (Ivars.empty())
4106 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004107
4108 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004109 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4110 e = Ivars.end(); i != e; i++) {
4111 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004112 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4113 unsigned GroupNo = 0;
4114 if (IvarDecl->isBitField()) {
4115 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4116 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4117 continue;
4118 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004119 Result += "\n";
4120 if (LangOpts.MicrosoftExt)
4121 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004122 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004123 if (LangOpts.MicrosoftExt &&
4124 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004125 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4126 Result += "__declspec(dllimport) ";
4127
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004128 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004129 if (IvarDecl->isBitField()) {
4130 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4131 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4132 }
4133 else
4134 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004135 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004136 }
4137}
4138
Fariborz Jahanian11671902012-02-07 17:11:38 +00004139//===----------------------------------------------------------------------===//
4140// Meta Data Emission
4141//===----------------------------------------------------------------------===//
4142
4143
4144/// RewriteImplementations - This routine rewrites all method implementations
4145/// and emits meta-data.
4146
4147void RewriteModernObjC::RewriteImplementations() {
4148 int ClsDefCount = ClassImplementation.size();
4149 int CatDefCount = CategoryImplementation.size();
4150
4151 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004152 for (int i = 0; i < ClsDefCount; i++) {
4153 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4154 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4155 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004156 assert(false &&
4157 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004158 RewriteImplementationDecl(OIMP);
4159 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004160
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004161 for (int i = 0; i < CatDefCount; i++) {
4162 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4163 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4164 if (CDecl->isImplicitInterfaceDecl())
4165 assert(false &&
4166 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004167 RewriteImplementationDecl(CIMP);
4168 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004169}
4170
4171void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4172 const std::string &Name,
4173 ValueDecl *VD, bool def) {
4174 assert(BlockByRefDeclNo.count(VD) &&
4175 "RewriteByRefString: ByRef decl missing");
4176 if (def)
4177 ResultStr += "struct ";
4178 ResultStr += "__Block_byref_" + Name +
4179 "_" + utostr(BlockByRefDeclNo[VD]) ;
4180}
4181
4182static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4183 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4184 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4185 return false;
4186}
4187
4188std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4189 StringRef funcName,
4190 std::string Tag) {
4191 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004192 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004193 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004194 SourceLocation BlockLoc = CE->getExprLoc();
4195 std::string S;
4196 ConvertSourceLocationToLineDirective(BlockLoc, S);
4197
4198 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4199 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004200
4201 BlockDecl *BD = CE->getBlockDecl();
4202
4203 if (isa<FunctionNoProtoType>(AFT)) {
4204 // No user-supplied arguments. Still need to pass in a pointer to the
4205 // block (to reference imported block decl refs).
4206 S += "(" + StructRef + " *__cself)";
4207 } else if (BD->param_empty()) {
4208 S += "(" + StructRef + " *__cself)";
4209 } else {
4210 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4211 assert(FT && "SynthesizeBlockFunc: No function proto");
4212 S += '(';
4213 // first add the implicit argument.
4214 S += StructRef + " *__cself, ";
4215 std::string ParamStr;
4216 for (BlockDecl::param_iterator AI = BD->param_begin(),
4217 E = BD->param_end(); AI != E; ++AI) {
4218 if (AI != BD->param_begin()) S += ", ";
4219 ParamStr = (*AI)->getNameAsString();
4220 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004221 (void)convertBlockPointerToFunctionPointer(QT);
4222 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004223 S += ParamStr;
4224 }
4225 if (FT->isVariadic()) {
4226 if (!BD->param_empty()) S += ", ";
4227 S += "...";
4228 }
4229 S += ')';
4230 }
4231 S += " {\n";
4232
4233 // Create local declarations to avoid rewriting all closure decl ref exprs.
4234 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004235 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004236 E = BlockByRefDecls.end(); I != E; ++I) {
4237 S += " ";
4238 std::string Name = (*I)->getNameAsString();
4239 std::string TypeString;
4240 RewriteByRefString(TypeString, Name, (*I));
4241 TypeString += " *";
4242 Name = TypeString + Name;
4243 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4244 }
4245 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004246 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004247 E = BlockByCopyDecls.end(); I != E; ++I) {
4248 S += " ";
4249 // Handle nested closure invocation. For example:
4250 //
4251 // void (^myImportedClosure)(void);
4252 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4253 //
4254 // void (^anotherClosure)(void);
4255 // anotherClosure = ^(void) {
4256 // myImportedClosure(); // import and invoke the closure
4257 // };
4258 //
4259 if (isTopLevelBlockPointerType((*I)->getType())) {
4260 RewriteBlockPointerTypeVariable(S, (*I));
4261 S += " = (";
4262 RewriteBlockPointerType(S, (*I)->getType());
4263 S += ")";
4264 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4265 }
4266 else {
4267 std::string Name = (*I)->getNameAsString();
4268 QualType QT = (*I)->getType();
4269 if (HasLocalVariableExternalStorage(*I))
4270 QT = Context->getPointerType(QT);
4271 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4272 S += Name + " = __cself->" +
4273 (*I)->getNameAsString() + "; // bound by copy\n";
4274 }
4275 }
4276 std::string RewrittenStr = RewrittenBlockExprs[CE];
4277 const char *cstr = RewrittenStr.c_str();
4278 while (*cstr++ != '{') ;
4279 S += cstr;
4280 S += "\n";
4281 return S;
4282}
4283
4284std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4285 StringRef funcName,
4286 std::string Tag) {
4287 std::string StructRef = "struct " + Tag;
4288 std::string S = "static void __";
4289
4290 S += funcName;
4291 S += "_block_copy_" + utostr(i);
4292 S += "(" + StructRef;
4293 S += "*dst, " + StructRef;
4294 S += "*src) {";
4295 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4296 E = ImportedBlockDecls.end(); I != E; ++I) {
4297 ValueDecl *VD = (*I);
4298 S += "_Block_object_assign((void*)&dst->";
4299 S += (*I)->getNameAsString();
4300 S += ", (void*)src->";
4301 S += (*I)->getNameAsString();
4302 if (BlockByRefDeclsPtrSet.count((*I)))
4303 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4304 else if (VD->getType()->isBlockPointerType())
4305 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4306 else
4307 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4308 }
4309 S += "}\n";
4310
4311 S += "\nstatic void __";
4312 S += funcName;
4313 S += "_block_dispose_" + utostr(i);
4314 S += "(" + StructRef;
4315 S += "*src) {";
4316 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4317 E = ImportedBlockDecls.end(); I != E; ++I) {
4318 ValueDecl *VD = (*I);
4319 S += "_Block_object_dispose((void*)src->";
4320 S += (*I)->getNameAsString();
4321 if (BlockByRefDeclsPtrSet.count((*I)))
4322 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4323 else if (VD->getType()->isBlockPointerType())
4324 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4325 else
4326 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4327 }
4328 S += "}\n";
4329 return S;
4330}
4331
4332std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4333 std::string Desc) {
4334 std::string S = "\nstruct " + Tag;
4335 std::string Constructor = " " + Tag;
4336
4337 S += " {\n struct __block_impl impl;\n";
4338 S += " struct " + Desc;
4339 S += "* Desc;\n";
4340
4341 Constructor += "(void *fp, "; // Invoke function pointer.
4342 Constructor += "struct " + Desc; // Descriptor pointer.
4343 Constructor += " *desc";
4344
4345 if (BlockDeclRefs.size()) {
4346 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004347 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004348 E = BlockByCopyDecls.end(); I != E; ++I) {
4349 S += " ";
4350 std::string FieldName = (*I)->getNameAsString();
4351 std::string ArgName = "_" + FieldName;
4352 // Handle nested closure invocation. For example:
4353 //
4354 // void (^myImportedBlock)(void);
4355 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4356 //
4357 // void (^anotherBlock)(void);
4358 // anotherBlock = ^(void) {
4359 // myImportedBlock(); // import and invoke the closure
4360 // };
4361 //
4362 if (isTopLevelBlockPointerType((*I)->getType())) {
4363 S += "struct __block_impl *";
4364 Constructor += ", void *" + ArgName;
4365 } else {
4366 QualType QT = (*I)->getType();
4367 if (HasLocalVariableExternalStorage(*I))
4368 QT = Context->getPointerType(QT);
4369 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4370 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4371 Constructor += ", " + ArgName;
4372 }
4373 S += FieldName + ";\n";
4374 }
4375 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004376 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004377 E = BlockByRefDecls.end(); I != E; ++I) {
4378 S += " ";
4379 std::string FieldName = (*I)->getNameAsString();
4380 std::string ArgName = "_" + FieldName;
4381 {
4382 std::string TypeString;
4383 RewriteByRefString(TypeString, FieldName, (*I));
4384 TypeString += " *";
4385 FieldName = TypeString + FieldName;
4386 ArgName = TypeString + ArgName;
4387 Constructor += ", " + ArgName;
4388 }
4389 S += FieldName + "; // by ref\n";
4390 }
4391 // Finish writing the constructor.
4392 Constructor += ", int flags=0)";
4393 // Initialize all "by copy" arguments.
4394 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004395 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004396 E = BlockByCopyDecls.end(); I != E; ++I) {
4397 std::string Name = (*I)->getNameAsString();
4398 if (firsTime) {
4399 Constructor += " : ";
4400 firsTime = false;
4401 }
4402 else
4403 Constructor += ", ";
4404 if (isTopLevelBlockPointerType((*I)->getType()))
4405 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4406 else
4407 Constructor += Name + "(_" + Name + ")";
4408 }
4409 // Initialize all "by ref" arguments.
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 std::string Name = (*I)->getNameAsString();
4413 if (firsTime) {
4414 Constructor += " : ";
4415 firsTime = false;
4416 }
4417 else
4418 Constructor += ", ";
4419 Constructor += Name + "(_" + Name + "->__forwarding)";
4420 }
4421
4422 Constructor += " {\n";
4423 if (GlobalVarDecl)
4424 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4425 else
4426 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4427 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4428
4429 Constructor += " Desc = desc;\n";
4430 } else {
4431 // Finish writing the constructor.
4432 Constructor += ", int flags=0) {\n";
4433 if (GlobalVarDecl)
4434 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4435 else
4436 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4437 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4438 Constructor += " Desc = desc;\n";
4439 }
4440 Constructor += " ";
4441 Constructor += "}\n";
4442 S += Constructor;
4443 S += "};\n";
4444 return S;
4445}
4446
4447std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4448 std::string ImplTag, int i,
4449 StringRef FunName,
4450 unsigned hasCopy) {
4451 std::string S = "\nstatic struct " + DescTag;
4452
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004453 S += " {\n size_t reserved;\n";
4454 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004455 if (hasCopy) {
4456 S += " void (*copy)(struct ";
4457 S += ImplTag; S += "*, struct ";
4458 S += ImplTag; S += "*);\n";
4459
4460 S += " void (*dispose)(struct ";
4461 S += ImplTag; S += "*);\n";
4462 }
4463 S += "} ";
4464
4465 S += DescTag + "_DATA = { 0, sizeof(struct ";
4466 S += ImplTag + ")";
4467 if (hasCopy) {
4468 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4469 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4470 }
4471 S += "};\n";
4472 return S;
4473}
4474
4475void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4476 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004477 bool RewriteSC = (GlobalVarDecl &&
4478 !Blocks.empty() &&
4479 GlobalVarDecl->getStorageClass() == SC_Static &&
4480 GlobalVarDecl->getType().getCVRQualifiers());
4481 if (RewriteSC) {
4482 std::string SC(" void __");
4483 SC += GlobalVarDecl->getNameAsString();
4484 SC += "() {}";
4485 InsertText(FunLocStart, SC);
4486 }
4487
4488 // Insert closures that were part of the function.
4489 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4490 CollectBlockDeclRefInfo(Blocks[i]);
4491 // Need to copy-in the inner copied-in variables not actually used in this
4492 // block.
4493 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004494 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004495 ValueDecl *VD = Exp->getDecl();
4496 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004497 if (!VD->hasAttr<BlocksAttr>()) {
4498 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4499 BlockByCopyDeclsPtrSet.insert(VD);
4500 BlockByCopyDecls.push_back(VD);
4501 }
4502 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004503 }
John McCall113bee02012-03-10 09:33:50 +00004504
4505 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004506 BlockByRefDeclsPtrSet.insert(VD);
4507 BlockByRefDecls.push_back(VD);
4508 }
John McCall113bee02012-03-10 09:33:50 +00004509
Fariborz Jahanian11671902012-02-07 17:11:38 +00004510 // imported objects in the inner blocks not used in the outer
4511 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004512 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004513 VD->getType()->isBlockPointerType())
4514 ImportedBlockDecls.insert(VD);
4515 }
4516
4517 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4518 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4519
4520 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4521
4522 InsertText(FunLocStart, CI);
4523
4524 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4525
4526 InsertText(FunLocStart, CF);
4527
4528 if (ImportedBlockDecls.size()) {
4529 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4530 InsertText(FunLocStart, HF);
4531 }
4532 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4533 ImportedBlockDecls.size() > 0);
4534 InsertText(FunLocStart, BD);
4535
4536 BlockDeclRefs.clear();
4537 BlockByRefDecls.clear();
4538 BlockByRefDeclsPtrSet.clear();
4539 BlockByCopyDecls.clear();
4540 BlockByCopyDeclsPtrSet.clear();
4541 ImportedBlockDecls.clear();
4542 }
4543 if (RewriteSC) {
4544 // Must insert any 'const/volatile/static here. Since it has been
4545 // removed as result of rewriting of block literals.
4546 std::string SC;
4547 if (GlobalVarDecl->getStorageClass() == SC_Static)
4548 SC = "static ";
4549 if (GlobalVarDecl->getType().isConstQualified())
4550 SC += "const ";
4551 if (GlobalVarDecl->getType().isVolatileQualified())
4552 SC += "volatile ";
4553 if (GlobalVarDecl->getType().isRestrictQualified())
4554 SC += "restrict ";
4555 InsertText(FunLocStart, SC);
4556 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004557 if (GlobalConstructionExp) {
4558 // extra fancy dance for global literal expression.
4559
4560 // Always the latest block expression on the block stack.
4561 std::string Tag = "__";
4562 Tag += FunName;
4563 Tag += "_block_impl_";
4564 Tag += utostr(Blocks.size()-1);
4565 std::string globalBuf = "static ";
4566 globalBuf += Tag; globalBuf += " ";
4567 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004568
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004569 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004570 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004571 PrintingPolicy(LangOpts));
4572 globalBuf += constructorExprBuf.str();
4573 globalBuf += ";\n";
4574 InsertText(FunLocStart, globalBuf);
4575 GlobalConstructionExp = 0;
4576 }
4577
Fariborz Jahanian11671902012-02-07 17:11:38 +00004578 Blocks.clear();
4579 InnerDeclRefsCount.clear();
4580 InnerDeclRefs.clear();
4581 RewrittenBlockExprs.clear();
4582}
4583
4584void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004585 SourceLocation FunLocStart =
4586 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4587 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004588 StringRef FuncName = FD->getName();
4589
4590 SynthesizeBlockLiterals(FunLocStart, FuncName);
4591}
4592
4593static void BuildUniqueMethodName(std::string &Name,
4594 ObjCMethodDecl *MD) {
4595 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4596 Name = IFace->getName();
4597 Name += "__" + MD->getSelector().getAsString();
4598 // Convert colons to underscores.
4599 std::string::size_type loc = 0;
4600 while ((loc = Name.find(":", loc)) != std::string::npos)
4601 Name.replace(loc, 1, "_");
4602}
4603
4604void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4605 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4606 //SourceLocation FunLocStart = MD->getLocStart();
4607 SourceLocation FunLocStart = MD->getLocStart();
4608 std::string FuncName;
4609 BuildUniqueMethodName(FuncName, MD);
4610 SynthesizeBlockLiterals(FunLocStart, FuncName);
4611}
4612
4613void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4614 for (Stmt::child_range CI = S->children(); CI; ++CI)
4615 if (*CI) {
4616 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4617 GetBlockDeclRefExprs(CBE->getBody());
4618 else
4619 GetBlockDeclRefExprs(*CI);
4620 }
4621 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004622 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4623 if (DRE->refersToEnclosingLocal()) {
4624 // FIXME: Handle enums.
4625 if (!isa<FunctionDecl>(DRE->getDecl()))
4626 BlockDeclRefs.push_back(DRE);
4627 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4628 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004629 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004630 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004631
4632 return;
4633}
4634
Craig Topper5603df42013-07-05 19:34:19 +00004635void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4636 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004637 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4638 for (Stmt::child_range CI = S->children(); CI; ++CI)
4639 if (*CI) {
4640 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4641 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4642 GetInnerBlockDeclRefExprs(CBE->getBody(),
4643 InnerBlockDeclRefs,
4644 InnerContexts);
4645 }
4646 else
4647 GetInnerBlockDeclRefExprs(*CI,
4648 InnerBlockDeclRefs,
4649 InnerContexts);
4650
4651 }
4652 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004653 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4654 if (DRE->refersToEnclosingLocal()) {
4655 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4656 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4657 InnerBlockDeclRefs.push_back(DRE);
4658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4659 if (Var->isFunctionOrMethodVarDecl())
4660 ImportedLocalExternalDecls.insert(Var);
4661 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004662 }
4663
4664 return;
4665}
4666
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004667/// convertObjCTypeToCStyleType - This routine converts such objc types
4668/// as qualified objects, and blocks to their closest c/c++ types that
4669/// it can. It returns true if input type was modified.
4670bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4671 QualType oldT = T;
4672 convertBlockPointerToFunctionPointer(T);
4673 if (T->isFunctionPointerType()) {
4674 QualType PointeeTy;
4675 if (const PointerType* PT = T->getAs<PointerType>()) {
4676 PointeeTy = PT->getPointeeType();
4677 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4678 T = convertFunctionTypeOfBlocks(FT);
4679 T = Context->getPointerType(T);
4680 }
4681 }
4682 }
4683
4684 convertToUnqualifiedObjCType(T);
4685 return T != oldT;
4686}
4687
Fariborz Jahanian11671902012-02-07 17:11:38 +00004688/// convertFunctionTypeOfBlocks - This routine converts a function type
4689/// whose result type may be a block pointer or whose argument type(s)
4690/// might be block pointers to an equivalent function type replacing
4691/// all block pointers to function pointers.
4692QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4693 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4694 // FTP will be null for closures that don't take arguments.
4695 // Generate a funky cast.
4696 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004697 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004698 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004699
4700 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004701 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4702 E = FTP->param_type_end();
4703 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004704 QualType t = *I;
4705 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004706 if (convertObjCTypeToCStyleType(t))
4707 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004708 ArgTypes.push_back(t);
4709 }
4710 }
4711 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004712 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004713 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004714 else FuncType = QualType(FT, 0);
4715 return FuncType;
4716}
4717
4718Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4719 // Navigate to relevant type information.
4720 const BlockPointerType *CPT = 0;
4721
4722 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4723 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004724 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4725 CPT = MExpr->getType()->getAs<BlockPointerType>();
4726 }
4727 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4728 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4729 }
4730 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4731 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4732 else if (const ConditionalOperator *CEXPR =
4733 dyn_cast<ConditionalOperator>(BlockExp)) {
4734 Expr *LHSExp = CEXPR->getLHS();
4735 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4736 Expr *RHSExp = CEXPR->getRHS();
4737 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4738 Expr *CONDExp = CEXPR->getCond();
4739 ConditionalOperator *CondExpr =
4740 new (Context) ConditionalOperator(CONDExp,
4741 SourceLocation(), cast<Expr>(LHSStmt),
4742 SourceLocation(), cast<Expr>(RHSStmt),
4743 Exp->getType(), VK_RValue, OK_Ordinary);
4744 return CondExpr;
4745 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4746 CPT = IRE->getType()->getAs<BlockPointerType>();
4747 } else if (const PseudoObjectExpr *POE
4748 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4749 CPT = POE->getType()->castAs<BlockPointerType>();
4750 } else {
4751 assert(1 && "RewriteBlockClass: Bad type");
4752 }
4753 assert(CPT && "RewriteBlockClass: Bad type");
4754 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4755 assert(FT && "RewriteBlockClass: Bad type");
4756 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4757 // FTP will be null for closures that don't take arguments.
4758
4759 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4760 SourceLocation(), SourceLocation(),
4761 &Context->Idents.get("__block_impl"));
4762 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4763
4764 // Generate a funky cast.
4765 SmallVector<QualType, 8> ArgTypes;
4766
4767 // Push the block argument type.
4768 ArgTypes.push_back(PtrBlock);
4769 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004770 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4771 E = FTP->param_type_end();
4772 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004773 QualType t = *I;
4774 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4775 if (!convertBlockPointerToFunctionPointer(t))
4776 convertToUnqualifiedObjCType(t);
4777 ArgTypes.push_back(t);
4778 }
4779 }
4780 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004781 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004782
4783 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4784
4785 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4786 CK_BitCast,
4787 const_cast<Expr*>(BlockExp));
4788 // Don't forget the parens to enforce the proper binding.
4789 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4790 BlkCast);
4791 //PE->dump();
4792
4793 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4794 SourceLocation(),
4795 &Context->Idents.get("FuncPtr"),
4796 Context->VoidPtrTy, 0,
4797 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004798 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004799 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4800 FD->getType(), VK_LValue,
4801 OK_Ordinary);
4802
4803
4804 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4805 CK_BitCast, ME);
4806 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4807
4808 SmallVector<Expr*, 8> BlkExprs;
4809 // Add the implicit argument.
4810 BlkExprs.push_back(BlkCast);
4811 // Add the user arguments.
4812 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4813 E = Exp->arg_end(); I != E; ++I) {
4814 BlkExprs.push_back(*I);
4815 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004816 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004817 Exp->getType(), VK_RValue,
4818 SourceLocation());
4819 return CE;
4820}
4821
4822// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004823// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004824// For example:
4825//
4826// int main() {
4827// __block Foo *f;
4828// __block int i;
4829//
4830// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004831// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004832// i = 77;
4833// };
4834//}
John McCall113bee02012-03-10 09:33:50 +00004835Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004836 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4837 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004838 ValueDecl *VD = DeclRefExp->getDecl();
4839 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004840
4841 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4842 SourceLocation(),
4843 &Context->Idents.get("__forwarding"),
4844 Context->VoidPtrTy, 0,
4845 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004846 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004847 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4848 FD, SourceLocation(),
4849 FD->getType(), VK_LValue,
4850 OK_Ordinary);
4851
4852 StringRef Name = VD->getName();
4853 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4854 &Context->Idents.get(Name),
4855 Context->VoidPtrTy, 0,
4856 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004857 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004858 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4859 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4860
4861
4862
4863 // Need parens to enforce precedence.
4864 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4865 DeclRefExp->getExprLoc(),
4866 ME);
4867 ReplaceStmt(DeclRefExp, PE);
4868 return PE;
4869}
4870
4871// Rewrites the imported local variable V with external storage
4872// (static, extern, etc.) as *V
4873//
4874Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4875 ValueDecl *VD = DRE->getDecl();
4876 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4877 if (!ImportedLocalExternalDecls.count(Var))
4878 return DRE;
4879 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4880 VK_LValue, OK_Ordinary,
4881 DRE->getLocation());
4882 // Need parens to enforce precedence.
4883 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4884 Exp);
4885 ReplaceStmt(DRE, PE);
4886 return PE;
4887}
4888
4889void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4890 SourceLocation LocStart = CE->getLParenLoc();
4891 SourceLocation LocEnd = CE->getRParenLoc();
4892
4893 // Need to avoid trying to rewrite synthesized casts.
4894 if (LocStart.isInvalid())
4895 return;
4896 // Need to avoid trying to rewrite casts contained in macros.
4897 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4898 return;
4899
4900 const char *startBuf = SM->getCharacterData(LocStart);
4901 const char *endBuf = SM->getCharacterData(LocEnd);
4902 QualType QT = CE->getType();
4903 const Type* TypePtr = QT->getAs<Type>();
4904 if (isa<TypeOfExprType>(TypePtr)) {
4905 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4906 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4907 std::string TypeAsString = "(";
4908 RewriteBlockPointerType(TypeAsString, QT);
4909 TypeAsString += ")";
4910 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4911 return;
4912 }
4913 // advance the location to startArgList.
4914 const char *argPtr = startBuf;
4915
4916 while (*argPtr++ && (argPtr < endBuf)) {
4917 switch (*argPtr) {
4918 case '^':
4919 // Replace the '^' with '*'.
4920 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4921 ReplaceText(LocStart, 1, "*");
4922 break;
4923 }
4924 }
4925 return;
4926}
4927
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004928void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4929 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004930 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4931 CastKind != CK_AnyPointerToBlockPointerCast)
4932 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004933
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004934 QualType QT = IC->getType();
4935 (void)convertBlockPointerToFunctionPointer(QT);
4936 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4937 std::string Str = "(";
4938 Str += TypeString;
4939 Str += ")";
4940 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4941
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004942 return;
4943}
4944
Fariborz Jahanian11671902012-02-07 17:11:38 +00004945void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4946 SourceLocation DeclLoc = FD->getLocation();
4947 unsigned parenCount = 0;
4948
4949 // We have 1 or more arguments that have closure pointers.
4950 const char *startBuf = SM->getCharacterData(DeclLoc);
4951 const char *startArgList = strchr(startBuf, '(');
4952
4953 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4954
4955 parenCount++;
4956 // advance the location to startArgList.
4957 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4958 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4959
4960 const char *argPtr = startArgList;
4961
4962 while (*argPtr++ && parenCount) {
4963 switch (*argPtr) {
4964 case '^':
4965 // Replace the '^' with '*'.
4966 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4967 ReplaceText(DeclLoc, 1, "*");
4968 break;
4969 case '(':
4970 parenCount++;
4971 break;
4972 case ')':
4973 parenCount--;
4974 break;
4975 }
4976 }
4977 return;
4978}
4979
4980bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4981 const FunctionProtoType *FTP;
4982 const PointerType *PT = QT->getAs<PointerType>();
4983 if (PT) {
4984 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4985 } else {
4986 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4987 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4988 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4989 }
4990 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004991 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4992 E = FTP->param_type_end();
4993 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004994 if (isTopLevelBlockPointerType(*I))
4995 return true;
4996 }
4997 return false;
4998}
4999
5000bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5001 const FunctionProtoType *FTP;
5002 const PointerType *PT = QT->getAs<PointerType>();
5003 if (PT) {
5004 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5005 } else {
5006 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5007 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5008 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5009 }
5010 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005011 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5012 E = FTP->param_type_end();
5013 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005014 if ((*I)->isObjCQualifiedIdType())
5015 return true;
5016 if ((*I)->isObjCObjectPointerType() &&
5017 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5018 return true;
5019 }
5020
5021 }
5022 return false;
5023}
5024
5025void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5026 const char *&RParen) {
5027 const char *argPtr = strchr(Name, '(');
5028 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5029
5030 LParen = argPtr; // output the start.
5031 argPtr++; // skip past the left paren.
5032 unsigned parenCount = 1;
5033
5034 while (*argPtr && parenCount) {
5035 switch (*argPtr) {
5036 case '(': parenCount++; break;
5037 case ')': parenCount--; break;
5038 default: break;
5039 }
5040 if (parenCount) argPtr++;
5041 }
5042 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5043 RParen = argPtr; // output the end
5044}
5045
5046void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5048 RewriteBlockPointerFunctionArgs(FD);
5049 return;
5050 }
5051 // Handle Variables and Typedefs.
5052 SourceLocation DeclLoc = ND->getLocation();
5053 QualType DeclT;
5054 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5055 DeclT = VD->getType();
5056 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5057 DeclT = TDD->getUnderlyingType();
5058 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5059 DeclT = FD->getType();
5060 else
5061 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5062
5063 const char *startBuf = SM->getCharacterData(DeclLoc);
5064 const char *endBuf = startBuf;
5065 // scan backward (from the decl location) for the end of the previous decl.
5066 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5067 startBuf--;
5068 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5069 std::string buf;
5070 unsigned OrigLength=0;
5071 // *startBuf != '^' if we are dealing with a pointer to function that
5072 // may take block argument types (which will be handled below).
5073 if (*startBuf == '^') {
5074 // Replace the '^' with '*', computing a negative offset.
5075 buf = '*';
5076 startBuf++;
5077 OrigLength++;
5078 }
5079 while (*startBuf != ')') {
5080 buf += *startBuf;
5081 startBuf++;
5082 OrigLength++;
5083 }
5084 buf += ')';
5085 OrigLength++;
5086
5087 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5088 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5089 // Replace the '^' with '*' for arguments.
5090 // Replace id<P> with id/*<>*/
5091 DeclLoc = ND->getLocation();
5092 startBuf = SM->getCharacterData(DeclLoc);
5093 const char *argListBegin, *argListEnd;
5094 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5095 while (argListBegin < argListEnd) {
5096 if (*argListBegin == '^')
5097 buf += '*';
5098 else if (*argListBegin == '<') {
5099 buf += "/*";
5100 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005101 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005102 while (*argListBegin != '>') {
5103 buf += *argListBegin++;
5104 OrigLength++;
5105 }
5106 buf += *argListBegin;
5107 buf += "*/";
5108 }
5109 else
5110 buf += *argListBegin;
5111 argListBegin++;
5112 OrigLength++;
5113 }
5114 buf += ')';
5115 OrigLength++;
5116 }
5117 ReplaceText(Start, OrigLength, buf);
5118
5119 return;
5120}
5121
5122
5123/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5124/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5125/// struct Block_byref_id_object *src) {
5126/// _Block_object_assign (&_dest->object, _src->object,
5127/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5128/// [|BLOCK_FIELD_IS_WEAK]) // object
5129/// _Block_object_assign(&_dest->object, _src->object,
5130/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5131/// [|BLOCK_FIELD_IS_WEAK]) // block
5132/// }
5133/// And:
5134/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5135/// _Block_object_dispose(_src->object,
5136/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5137/// [|BLOCK_FIELD_IS_WEAK]) // object
5138/// _Block_object_dispose(_src->object,
5139/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5140/// [|BLOCK_FIELD_IS_WEAK]) // block
5141/// }
5142
5143std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5144 int flag) {
5145 std::string S;
5146 if (CopyDestroyCache.count(flag))
5147 return S;
5148 CopyDestroyCache.insert(flag);
5149 S = "static void __Block_byref_id_object_copy_";
5150 S += utostr(flag);
5151 S += "(void *dst, void *src) {\n";
5152
5153 // offset into the object pointer is computed as:
5154 // void * + void* + int + int + void* + void *
5155 unsigned IntSize =
5156 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5157 unsigned VoidPtrSize =
5158 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5159
5160 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5161 S += " _Block_object_assign((char*)dst + ";
5162 S += utostr(offset);
5163 S += ", *(void * *) ((char*)src + ";
5164 S += utostr(offset);
5165 S += "), ";
5166 S += utostr(flag);
5167 S += ");\n}\n";
5168
5169 S += "static void __Block_byref_id_object_dispose_";
5170 S += utostr(flag);
5171 S += "(void *src) {\n";
5172 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5173 S += utostr(offset);
5174 S += "), ";
5175 S += utostr(flag);
5176 S += ");\n}\n";
5177 return S;
5178}
5179
5180/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5181/// the declaration into:
5182/// struct __Block_byref_ND {
5183/// void *__isa; // NULL for everything except __weak pointers
5184/// struct __Block_byref_ND *__forwarding;
5185/// int32_t __flags;
5186/// int32_t __size;
5187/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5188/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5189/// typex ND;
5190/// };
5191///
5192/// It then replaces declaration of ND variable with:
5193/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5194/// __size=sizeof(struct __Block_byref_ND),
5195/// ND=initializer-if-any};
5196///
5197///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005198void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5199 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005200 int flag = 0;
5201 int isa = 0;
5202 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5203 if (DeclLoc.isInvalid())
5204 // If type location is missing, it is because of missing type (a warning).
5205 // Use variable's location which is good for this case.
5206 DeclLoc = ND->getLocation();
5207 const char *startBuf = SM->getCharacterData(DeclLoc);
5208 SourceLocation X = ND->getLocEnd();
5209 X = SM->getExpansionLoc(X);
5210 const char *endBuf = SM->getCharacterData(X);
5211 std::string Name(ND->getNameAsString());
5212 std::string ByrefType;
5213 RewriteByRefString(ByrefType, Name, ND, true);
5214 ByrefType += " {\n";
5215 ByrefType += " void *__isa;\n";
5216 RewriteByRefString(ByrefType, Name, ND);
5217 ByrefType += " *__forwarding;\n";
5218 ByrefType += " int __flags;\n";
5219 ByrefType += " int __size;\n";
5220 // Add void *__Block_byref_id_object_copy;
5221 // void *__Block_byref_id_object_dispose; if needed.
5222 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005223 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005224 if (HasCopyAndDispose) {
5225 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5226 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5227 }
5228
5229 QualType T = Ty;
5230 (void)convertBlockPointerToFunctionPointer(T);
5231 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5232
5233 ByrefType += " " + Name + ";\n";
5234 ByrefType += "};\n";
5235 // Insert this type in global scope. It is needed by helper function.
5236 SourceLocation FunLocStart;
5237 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005238 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005239 else {
5240 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5241 FunLocStart = CurMethodDef->getLocStart();
5242 }
5243 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005244
Fariborz Jahanian11671902012-02-07 17:11:38 +00005245 if (Ty.isObjCGCWeak()) {
5246 flag |= BLOCK_FIELD_IS_WEAK;
5247 isa = 1;
5248 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005249 if (HasCopyAndDispose) {
5250 flag = BLOCK_BYREF_CALLER;
5251 QualType Ty = ND->getType();
5252 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5253 if (Ty->isBlockPointerType())
5254 flag |= BLOCK_FIELD_IS_BLOCK;
5255 else
5256 flag |= BLOCK_FIELD_IS_OBJECT;
5257 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5258 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005259 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005260 }
5261
5262 // struct __Block_byref_ND ND =
5263 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5264 // initializer-if-any};
5265 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005266 // FIXME. rewriter does not support __block c++ objects which
5267 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005268 if (hasInit)
5269 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5270 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5271 if (CXXDecl && CXXDecl->isDefaultConstructor())
5272 hasInit = false;
5273 }
5274
Fariborz Jahanian11671902012-02-07 17:11:38 +00005275 unsigned flags = 0;
5276 if (HasCopyAndDispose)
5277 flags |= BLOCK_HAS_COPY_DISPOSE;
5278 Name = ND->getNameAsString();
5279 ByrefType.clear();
5280 RewriteByRefString(ByrefType, Name, ND);
5281 std::string ForwardingCastType("(");
5282 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005283 ByrefType += " " + Name + " = {(void*)";
5284 ByrefType += utostr(isa);
5285 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5286 ByrefType += utostr(flags);
5287 ByrefType += ", ";
5288 ByrefType += "sizeof(";
5289 RewriteByRefString(ByrefType, Name, ND);
5290 ByrefType += ")";
5291 if (HasCopyAndDispose) {
5292 ByrefType += ", __Block_byref_id_object_copy_";
5293 ByrefType += utostr(flag);
5294 ByrefType += ", __Block_byref_id_object_dispose_";
5295 ByrefType += utostr(flag);
5296 }
5297
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005298 if (!firstDecl) {
5299 // In multiple __block declarations, and for all but 1st declaration,
5300 // find location of the separating comma. This would be start location
5301 // where new text is to be inserted.
5302 DeclLoc = ND->getLocation();
5303 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5304 const char *commaBuf = startDeclBuf;
5305 while (*commaBuf != ',')
5306 commaBuf--;
5307 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5308 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5309 startBuf = commaBuf;
5310 }
5311
Fariborz Jahanian11671902012-02-07 17:11:38 +00005312 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005313 ByrefType += "};\n";
5314 unsigned nameSize = Name.size();
5315 // for block or function pointer declaration. Name is aleady
5316 // part of the declaration.
5317 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5318 nameSize = 1;
5319 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5320 }
5321 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005322 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005323 SourceLocation startLoc;
5324 Expr *E = ND->getInit();
5325 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5326 startLoc = ECE->getLParenLoc();
5327 else
5328 startLoc = E->getLocStart();
5329 startLoc = SM->getExpansionLoc(startLoc);
5330 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005331 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005332
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005333 const char separator = lastDecl ? ';' : ',';
5334 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5335 const char *separatorBuf = strchr(startInitializerBuf, separator);
5336 assert((*separatorBuf == separator) &&
5337 "RewriteByRefVar: can't find ';' or ','");
5338 SourceLocation separatorLoc =
5339 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5340
5341 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005342 }
5343 return;
5344}
5345
5346void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5347 // Add initializers for any closure decl refs.
5348 GetBlockDeclRefExprs(Exp->getBody());
5349 if (BlockDeclRefs.size()) {
5350 // Unique all "by copy" declarations.
5351 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005352 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005353 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5354 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5355 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5356 }
5357 }
5358 // Unique all "by ref" declarations.
5359 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005360 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005361 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5362 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5363 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5364 }
5365 }
5366 // Find any imported blocks...they will need special attention.
5367 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005368 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005369 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5370 BlockDeclRefs[i]->getType()->isBlockPointerType())
5371 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5372 }
5373}
5374
5375FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5376 IdentifierInfo *ID = &Context->Idents.get(name);
5377 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5378 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5379 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005380 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005381}
5382
5383Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005384 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005385
Fariborz Jahanian11671902012-02-07 17:11:38 +00005386 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005387
Fariborz Jahanian11671902012-02-07 17:11:38 +00005388 Blocks.push_back(Exp);
5389
5390 CollectBlockDeclRefInfo(Exp);
5391
5392 // Add inner imported variables now used in current block.
5393 int countOfInnerDecls = 0;
5394 if (!InnerBlockDeclRefs.empty()) {
5395 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005396 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005397 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005398 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005399 // We need to save the copied-in variables in nested
5400 // blocks because it is needed at the end for some of the API generations.
5401 // See SynthesizeBlockLiterals routine.
5402 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5403 BlockDeclRefs.push_back(Exp);
5404 BlockByCopyDeclsPtrSet.insert(VD);
5405 BlockByCopyDecls.push_back(VD);
5406 }
John McCall113bee02012-03-10 09:33:50 +00005407 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005408 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5409 BlockDeclRefs.push_back(Exp);
5410 BlockByRefDeclsPtrSet.insert(VD);
5411 BlockByRefDecls.push_back(VD);
5412 }
5413 }
5414 // Find any imported blocks...they will need special attention.
5415 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005416 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005417 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5418 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5419 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5420 }
5421 InnerDeclRefsCount.push_back(countOfInnerDecls);
5422
5423 std::string FuncName;
5424
5425 if (CurFunctionDef)
5426 FuncName = CurFunctionDef->getNameAsString();
5427 else if (CurMethodDef)
5428 BuildUniqueMethodName(FuncName, CurMethodDef);
5429 else if (GlobalVarDecl)
5430 FuncName = std::string(GlobalVarDecl->getNameAsString());
5431
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005432 bool GlobalBlockExpr =
5433 block->getDeclContext()->getRedeclContext()->isFileContext();
5434
5435 if (GlobalBlockExpr && !GlobalVarDecl) {
5436 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5437 GlobalBlockExpr = false;
5438 }
5439
Fariborz Jahanian11671902012-02-07 17:11:38 +00005440 std::string BlockNumber = utostr(Blocks.size()-1);
5441
Fariborz Jahanian11671902012-02-07 17:11:38 +00005442 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5443
5444 // Get a pointer to the function type so we can cast appropriately.
5445 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5446 QualType FType = Context->getPointerType(BFT);
5447
5448 FunctionDecl *FD;
5449 Expr *NewRep;
5450
Benjamin Kramer60509af2013-09-09 14:48:42 +00005451 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005452 std::string Tag;
5453
5454 if (GlobalBlockExpr)
5455 Tag = "__global_";
5456 else
5457 Tag = "__";
5458 Tag += FuncName + "_block_impl_" + BlockNumber;
5459
Fariborz Jahanian11671902012-02-07 17:11:38 +00005460 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005461 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005462 SourceLocation());
5463
5464 SmallVector<Expr*, 4> InitExprs;
5465
5466 // Initialize the block function.
5467 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005468 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5469 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005470 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5471 CK_BitCast, Arg);
5472 InitExprs.push_back(castExpr);
5473
5474 // Initialize the block descriptor.
5475 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5476
5477 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5478 SourceLocation(), SourceLocation(),
5479 &Context->Idents.get(DescData.c_str()),
5480 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005481 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005482 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005483 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005484 Context->VoidPtrTy,
5485 VK_LValue,
5486 SourceLocation()),
5487 UO_AddrOf,
5488 Context->getPointerType(Context->VoidPtrTy),
5489 VK_RValue, OK_Ordinary,
5490 SourceLocation());
5491 InitExprs.push_back(DescRefExpr);
5492
5493 // Add initializers for any closure decl refs.
5494 if (BlockDeclRefs.size()) {
5495 Expr *Exp;
5496 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005497 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005498 E = BlockByCopyDecls.end(); I != E; ++I) {
5499 if (isObjCType((*I)->getType())) {
5500 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5501 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005502 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5503 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005504 if (HasLocalVariableExternalStorage(*I)) {
5505 QualType QT = (*I)->getType();
5506 QT = Context->getPointerType(QT);
5507 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5508 OK_Ordinary, SourceLocation());
5509 }
5510 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5511 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005512 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5513 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005514 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5515 CK_BitCast, Arg);
5516 } else {
5517 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005518 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5519 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005520 if (HasLocalVariableExternalStorage(*I)) {
5521 QualType QT = (*I)->getType();
5522 QT = Context->getPointerType(QT);
5523 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5524 OK_Ordinary, SourceLocation());
5525 }
5526
5527 }
5528 InitExprs.push_back(Exp);
5529 }
5530 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005531 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005532 E = BlockByRefDecls.end(); I != E; ++I) {
5533 ValueDecl *ND = (*I);
5534 std::string Name(ND->getNameAsString());
5535 std::string RecName;
5536 RewriteByRefString(RecName, Name, ND, true);
5537 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5538 + sizeof("struct"));
5539 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5540 SourceLocation(), SourceLocation(),
5541 II);
5542 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5543 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5544
5545 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005546 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005547 SourceLocation());
5548 bool isNestedCapturedVar = false;
5549 if (block)
5550 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5551 ce = block->capture_end(); ci != ce; ++ci) {
5552 const VarDecl *variable = ci->getVariable();
5553 if (variable == ND && ci->isNested()) {
5554 assert (ci->isByRef() &&
5555 "SynthBlockInitExpr - captured block variable is not byref");
5556 isNestedCapturedVar = true;
5557 break;
5558 }
5559 }
5560 // captured nested byref variable has its address passed. Do not take
5561 // its address again.
5562 if (!isNestedCapturedVar)
5563 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5564 Context->getPointerType(Exp->getType()),
5565 VK_RValue, OK_Ordinary, SourceLocation());
5566 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5567 InitExprs.push_back(Exp);
5568 }
5569 }
5570 if (ImportedBlockDecls.size()) {
5571 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5572 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5573 unsigned IntSize =
5574 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5575 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5576 Context->IntTy, SourceLocation());
5577 InitExprs.push_back(FlagExp);
5578 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005579 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005580 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005581
5582 if (GlobalBlockExpr) {
5583 assert (GlobalConstructionExp == 0 &&
5584 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5585 GlobalConstructionExp = NewRep;
5586 NewRep = DRE;
5587 }
5588
Fariborz Jahanian11671902012-02-07 17:11:38 +00005589 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5590 Context->getPointerType(NewRep->getType()),
5591 VK_RValue, OK_Ordinary, SourceLocation());
5592 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5593 NewRep);
5594 BlockDeclRefs.clear();
5595 BlockByRefDecls.clear();
5596 BlockByRefDeclsPtrSet.clear();
5597 BlockByCopyDecls.clear();
5598 BlockByCopyDeclsPtrSet.clear();
5599 ImportedBlockDecls.clear();
5600 return NewRep;
5601}
5602
5603bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5604 if (const ObjCForCollectionStmt * CS =
5605 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5606 return CS->getElement() == DS;
5607 return false;
5608}
5609
5610//===----------------------------------------------------------------------===//
5611// Function Body / Expression rewriting
5612//===----------------------------------------------------------------------===//
5613
5614Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5615 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5616 isa<DoStmt>(S) || isa<ForStmt>(S))
5617 Stmts.push_back(S);
5618 else if (isa<ObjCForCollectionStmt>(S)) {
5619 Stmts.push_back(S);
5620 ObjCBcLabelNo.push_back(++BcLabelCount);
5621 }
5622
5623 // Pseudo-object operations and ivar references need special
5624 // treatment because we're going to recursively rewrite them.
5625 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5626 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5627 return RewritePropertyOrImplicitSetter(PseudoOp);
5628 } else {
5629 return RewritePropertyOrImplicitGetter(PseudoOp);
5630 }
5631 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5632 return RewriteObjCIvarRefExpr(IvarRefExpr);
5633 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005634 else if (isa<OpaqueValueExpr>(S))
5635 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005636
5637 SourceRange OrigStmtRange = S->getSourceRange();
5638
5639 // Perform a bottom up rewrite of all children.
5640 for (Stmt::child_range CI = S->children(); CI; ++CI)
5641 if (*CI) {
5642 Stmt *childStmt = (*CI);
5643 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5644 if (newStmt) {
5645 *CI = newStmt;
5646 }
5647 }
5648
5649 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005650 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005651 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5652 InnerContexts.insert(BE->getBlockDecl());
5653 ImportedLocalExternalDecls.clear();
5654 GetInnerBlockDeclRefExprs(BE->getBody(),
5655 InnerBlockDeclRefs, InnerContexts);
5656 // Rewrite the block body in place.
5657 Stmt *SaveCurrentBody = CurrentBody;
5658 CurrentBody = BE->getBody();
5659 PropParentMap = 0;
5660 // block literal on rhs of a property-dot-sytax assignment
5661 // must be replaced by its synthesize ast so getRewrittenText
5662 // works as expected. In this case, what actually ends up on RHS
5663 // is the blockTranscribed which is the helper function for the
5664 // block literal; as in: self.c = ^() {[ace ARR];};
5665 bool saveDisableReplaceStmt = DisableReplaceStmt;
5666 DisableReplaceStmt = false;
5667 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5668 DisableReplaceStmt = saveDisableReplaceStmt;
5669 CurrentBody = SaveCurrentBody;
5670 PropParentMap = 0;
5671 ImportedLocalExternalDecls.clear();
5672 // Now we snarf the rewritten text and stash it away for later use.
5673 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5674 RewrittenBlockExprs[BE] = Str;
5675
5676 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5677
5678 //blockTranscribed->dump();
5679 ReplaceStmt(S, blockTranscribed);
5680 return blockTranscribed;
5681 }
5682 // Handle specific things.
5683 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5684 return RewriteAtEncode(AtEncode);
5685
5686 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5687 return RewriteAtSelector(AtSelector);
5688
5689 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5690 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005691
5692 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5693 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005694
Patrick Beard0caa3942012-04-19 00:25:12 +00005695 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5696 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005697
5698 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5699 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005700
5701 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5702 dyn_cast<ObjCDictionaryLiteral>(S))
5703 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005704
5705 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5706#if 0
5707 // Before we rewrite it, put the original message expression in a comment.
5708 SourceLocation startLoc = MessExpr->getLocStart();
5709 SourceLocation endLoc = MessExpr->getLocEnd();
5710
5711 const char *startBuf = SM->getCharacterData(startLoc);
5712 const char *endBuf = SM->getCharacterData(endLoc);
5713
5714 std::string messString;
5715 messString += "// ";
5716 messString.append(startBuf, endBuf-startBuf+1);
5717 messString += "\n";
5718
5719 // FIXME: Missing definition of
5720 // InsertText(clang::SourceLocation, char const*, unsigned int).
5721 // InsertText(startLoc, messString.c_str(), messString.size());
5722 // Tried this, but it didn't work either...
5723 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5724#endif
5725 return RewriteMessageExpr(MessExpr);
5726 }
5727
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005728 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5729 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5730 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5731 }
5732
Fariborz Jahanian11671902012-02-07 17:11:38 +00005733 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5734 return RewriteObjCTryStmt(StmtTry);
5735
5736 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5737 return RewriteObjCSynchronizedStmt(StmtTry);
5738
5739 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5740 return RewriteObjCThrowStmt(StmtThrow);
5741
5742 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5743 return RewriteObjCProtocolExpr(ProtocolExp);
5744
5745 if (ObjCForCollectionStmt *StmtForCollection =
5746 dyn_cast<ObjCForCollectionStmt>(S))
5747 return RewriteObjCForCollectionStmt(StmtForCollection,
5748 OrigStmtRange.getEnd());
5749 if (BreakStmt *StmtBreakStmt =
5750 dyn_cast<BreakStmt>(S))
5751 return RewriteBreakStmt(StmtBreakStmt);
5752 if (ContinueStmt *StmtContinueStmt =
5753 dyn_cast<ContinueStmt>(S))
5754 return RewriteContinueStmt(StmtContinueStmt);
5755
5756 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5757 // and cast exprs.
5758 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5759 // FIXME: What we're doing here is modifying the type-specifier that
5760 // precedes the first Decl. In the future the DeclGroup should have
5761 // a separate type-specifier that we can rewrite.
5762 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5763 // the context of an ObjCForCollectionStmt. For example:
5764 // NSArray *someArray;
5765 // for (id <FooProtocol> index in someArray) ;
5766 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5767 // and it depends on the original text locations/positions.
5768 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5769 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5770
5771 // Blocks rewrite rules.
5772 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5773 DI != DE; ++DI) {
5774 Decl *SD = *DI;
5775 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5776 if (isTopLevelBlockPointerType(ND->getType()))
5777 RewriteBlockPointerDecl(ND);
5778 else if (ND->getType()->isFunctionPointerType())
5779 CheckFunctionPointerDecl(ND->getType(), ND);
5780 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5781 if (VD->hasAttr<BlocksAttr>()) {
5782 static unsigned uniqueByrefDeclCount = 0;
5783 assert(!BlockByRefDeclNo.count(ND) &&
5784 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5785 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005786 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005787 }
5788 else
5789 RewriteTypeOfDecl(VD);
5790 }
5791 }
5792 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5793 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5794 RewriteBlockPointerDecl(TD);
5795 else if (TD->getUnderlyingType()->isFunctionPointerType())
5796 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5797 }
5798 }
5799 }
5800
5801 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5802 RewriteObjCQualifiedInterfaceTypes(CE);
5803
5804 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5805 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5806 assert(!Stmts.empty() && "Statement stack is empty");
5807 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5808 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5809 && "Statement stack mismatch");
5810 Stmts.pop_back();
5811 }
5812 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005813 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5814 ValueDecl *VD = DRE->getDecl();
5815 if (VD->hasAttr<BlocksAttr>())
5816 return RewriteBlockDeclRefExpr(DRE);
5817 if (HasLocalVariableExternalStorage(VD))
5818 return RewriteLocalVariableExternalStorage(DRE);
5819 }
5820
5821 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5822 if (CE->getCallee()->getType()->isBlockPointerType()) {
5823 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5824 ReplaceStmt(S, BlockCall);
5825 return BlockCall;
5826 }
5827 }
5828 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5829 RewriteCastExpr(CE);
5830 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005831 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5832 RewriteImplicitCastObjCExpr(ICE);
5833 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005834#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005835
Fariborz Jahanian11671902012-02-07 17:11:38 +00005836 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5837 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5838 ICE->getSubExpr(),
5839 SourceLocation());
5840 // Get the new text.
5841 std::string SStr;
5842 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005843 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005844 const std::string &Str = Buf.str();
5845
5846 printf("CAST = %s\n", &Str[0]);
5847 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5848 delete S;
5849 return Replacement;
5850 }
5851#endif
5852 // Return this stmt unmodified.
5853 return S;
5854}
5855
5856void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5857 for (RecordDecl::field_iterator i = RD->field_begin(),
5858 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005859 FieldDecl *FD = *i;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005860 if (isTopLevelBlockPointerType(FD->getType()))
5861 RewriteBlockPointerDecl(FD);
5862 if (FD->getType()->isObjCQualifiedIdType() ||
5863 FD->getType()->isObjCQualifiedInterfaceType())
5864 RewriteObjCQualifiedInterfaceTypes(FD);
5865 }
5866}
5867
5868/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5869/// main file of the input.
5870void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5871 switch (D->getKind()) {
5872 case Decl::Function: {
5873 FunctionDecl *FD = cast<FunctionDecl>(D);
5874 if (FD->isOverloadedOperator())
5875 return;
5876
5877 // Since function prototypes don't have ParmDecl's, we check the function
5878 // prototype. This enables us to rewrite function declarations and
5879 // definitions using the same code.
5880 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5881
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005882 if (!FD->isThisDeclarationADefinition())
5883 break;
5884
Fariborz Jahanian11671902012-02-07 17:11:38 +00005885 // FIXME: If this should support Obj-C++, support CXXTryStmt
5886 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5887 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005888 CurrentBody = Body;
5889 Body =
5890 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5891 FD->setBody(Body);
5892 CurrentBody = 0;
5893 if (PropParentMap) {
5894 delete PropParentMap;
5895 PropParentMap = 0;
5896 }
5897 // This synthesizes and inserts the block "impl" struct, invoke function,
5898 // and any copy/dispose helper functions.
5899 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005900 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005901 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005902 }
5903 break;
5904 }
5905 case Decl::ObjCMethod: {
5906 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5907 if (CompoundStmt *Body = MD->getCompoundBody()) {
5908 CurMethodDef = MD;
5909 CurrentBody = Body;
5910 Body =
5911 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5912 MD->setBody(Body);
5913 CurrentBody = 0;
5914 if (PropParentMap) {
5915 delete PropParentMap;
5916 PropParentMap = 0;
5917 }
5918 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005919 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005920 CurMethodDef = 0;
5921 }
5922 break;
5923 }
5924 case Decl::ObjCImplementation: {
5925 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5926 ClassImplementation.push_back(CI);
5927 break;
5928 }
5929 case Decl::ObjCCategoryImpl: {
5930 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5931 CategoryImplementation.push_back(CI);
5932 break;
5933 }
5934 case Decl::Var: {
5935 VarDecl *VD = cast<VarDecl>(D);
5936 RewriteObjCQualifiedInterfaceTypes(VD);
5937 if (isTopLevelBlockPointerType(VD->getType()))
5938 RewriteBlockPointerDecl(VD);
5939 else if (VD->getType()->isFunctionPointerType()) {
5940 CheckFunctionPointerDecl(VD->getType(), VD);
5941 if (VD->getInit()) {
5942 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5943 RewriteCastExpr(CE);
5944 }
5945 }
5946 } else if (VD->getType()->isRecordType()) {
5947 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5948 if (RD->isCompleteDefinition())
5949 RewriteRecordBody(RD);
5950 }
5951 if (VD->getInit()) {
5952 GlobalVarDecl = VD;
5953 CurrentBody = VD->getInit();
5954 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5955 CurrentBody = 0;
5956 if (PropParentMap) {
5957 delete PropParentMap;
5958 PropParentMap = 0;
5959 }
5960 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5961 GlobalVarDecl = 0;
5962
5963 // This is needed for blocks.
5964 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5965 RewriteCastExpr(CE);
5966 }
5967 }
5968 break;
5969 }
5970 case Decl::TypeAlias:
5971 case Decl::Typedef: {
5972 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5973 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5974 RewriteBlockPointerDecl(TD);
5975 else if (TD->getUnderlyingType()->isFunctionPointerType())
5976 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005977 else
5978 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005979 }
5980 break;
5981 }
5982 case Decl::CXXRecord:
5983 case Decl::Record: {
5984 RecordDecl *RD = cast<RecordDecl>(D);
5985 if (RD->isCompleteDefinition())
5986 RewriteRecordBody(RD);
5987 break;
5988 }
5989 default:
5990 break;
5991 }
5992 // Nothing yet.
5993}
5994
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005995/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5996/// protocol reference symbols in the for of:
5997/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5998static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5999 ObjCProtocolDecl *PDecl,
6000 std::string &Result) {
6001 // Also output .objc_protorefs$B section and its meta-data.
6002 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00006003 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006004 Result += "struct _protocol_t *";
6005 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6006 Result += PDecl->getNameAsString();
6007 Result += " = &";
6008 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6009 Result += ";\n";
6010}
6011
Fariborz Jahanian11671902012-02-07 17:11:38 +00006012void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6013 if (Diags.hasErrorOccurred())
6014 return;
6015
6016 RewriteInclude();
6017
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006018 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006019 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006020 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006021 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006022 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6023 HandleTopLevelSingleDecl(FDecl);
6024 }
6025
Fariborz Jahanian11671902012-02-07 17:11:38 +00006026 // Here's a great place to add any extra declarations that may be needed.
6027 // Write out meta data for each @protocol(<expr>).
6028 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006029 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006030 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006031 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6032 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006033
6034 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006035
6036 if (ClassImplementation.size() || CategoryImplementation.size())
6037 RewriteImplementations();
6038
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006039 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6040 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6041 // Write struct declaration for the class matching its ivar declarations.
6042 // Note that for modern abi, this is postponed until the end of TU
6043 // because class extensions and the implementation might declare their own
6044 // private ivars.
6045 RewriteInterfaceDecl(CDecl);
6046 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006047
Fariborz Jahanian11671902012-02-07 17:11:38 +00006048 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6049 // we are done.
6050 if (const RewriteBuffer *RewriteBuf =
6051 Rewrite.getRewriteBufferFor(MainFileID)) {
6052 //printf("Changed:\n");
6053 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6054 } else {
6055 llvm::errs() << "No changes\n";
6056 }
6057
6058 if (ClassImplementation.size() || CategoryImplementation.size() ||
6059 ProtocolExprDecls.size()) {
6060 // Rewrite Objective-c meta data*
6061 std::string ResultStr;
6062 RewriteMetaDataIntoBuffer(ResultStr);
6063 // Emit metadata.
6064 *OutFile << ResultStr;
6065 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006066 // Emit ImageInfo;
6067 {
6068 std::string ResultStr;
6069 WriteImageInfo(ResultStr);
6070 *OutFile << ResultStr;
6071 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006072 OutFile->flush();
6073}
6074
6075void RewriteModernObjC::Initialize(ASTContext &context) {
6076 InitializeCommon(context);
6077
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006078 Preamble += "#ifndef __OBJC2__\n";
6079 Preamble += "#define __OBJC2__\n";
6080 Preamble += "#endif\n";
6081
Fariborz Jahanian11671902012-02-07 17:11:38 +00006082 // declaring objc_selector outside the parameter list removes a silly
6083 // scope related warning...
6084 if (IsHeader)
6085 Preamble = "#pragma once\n";
6086 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006087 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6088 Preamble += "\n\tstruct objc_object *superClass; ";
6089 // Add a constructor for creating temporary objects.
6090 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6091 Preamble += ": object(o), superClass(s) {} ";
6092 Preamble += "\n};\n";
6093
Fariborz Jahanian11671902012-02-07 17:11:38 +00006094 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006095 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006096 // These are currently generated.
6097 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006098 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006099 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006100 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6101 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006102 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006103 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006104 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6105 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006106 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006107
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006108 // These need be generated for performance. Currently they are not,
6109 // using API calls instead.
6110 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6111 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6112 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6113
Fariborz Jahanian11671902012-02-07 17:11:38 +00006114 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006115 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6116 Preamble += "typedef struct objc_object Protocol;\n";
6117 Preamble += "#define _REWRITER_typedef_Protocol\n";
6118 Preamble += "#endif\n";
6119 if (LangOpts.MicrosoftExt) {
6120 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6121 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006122 }
6123 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006124 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006125
6126 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6127 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6128 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6129 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6130 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6131
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006132 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006133 Preamble += "(const char *);\n";
6134 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6135 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006136 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006137 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006138 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006139 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006140 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6141 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006142 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006143 Preamble += "#ifdef _WIN64\n";
6144 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6145 Preamble += "#else\n";
6146 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6147 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006148 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6149 Preamble += "struct __objcFastEnumerationState {\n\t";
6150 Preamble += "unsigned long state;\n\t";
6151 Preamble += "void **itemsPtr;\n\t";
6152 Preamble += "unsigned long *mutationsPtr;\n\t";
6153 Preamble += "unsigned long extra[5];\n};\n";
6154 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6155 Preamble += "#define __FASTENUMERATIONSTATE\n";
6156 Preamble += "#endif\n";
6157 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6158 Preamble += "struct __NSConstantStringImpl {\n";
6159 Preamble += " int *isa;\n";
6160 Preamble += " int flags;\n";
6161 Preamble += " char *str;\n";
6162 Preamble += " long length;\n";
6163 Preamble += "};\n";
6164 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6165 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6166 Preamble += "#else\n";
6167 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6168 Preamble += "#endif\n";
6169 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6170 Preamble += "#endif\n";
6171 // Blocks preamble.
6172 Preamble += "#ifndef BLOCK_IMPL\n";
6173 Preamble += "#define BLOCK_IMPL\n";
6174 Preamble += "struct __block_impl {\n";
6175 Preamble += " void *isa;\n";
6176 Preamble += " int Flags;\n";
6177 Preamble += " int Reserved;\n";
6178 Preamble += " void *FuncPtr;\n";
6179 Preamble += "};\n";
6180 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6181 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6182 Preamble += "extern \"C\" __declspec(dllexport) "
6183 "void _Block_object_assign(void *, const void *, const int);\n";
6184 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6185 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6186 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6187 Preamble += "#else\n";
6188 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6189 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6190 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6191 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6192 Preamble += "#endif\n";
6193 Preamble += "#endif\n";
6194 if (LangOpts.MicrosoftExt) {
6195 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6196 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6197 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6198 Preamble += "#define __attribute__(X)\n";
6199 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006200 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006201 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006202 Preamble += "#endif\n";
6203 Preamble += "#ifndef __block\n";
6204 Preamble += "#define __block\n";
6205 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006206 }
6207 else {
6208 Preamble += "#define __block\n";
6209 Preamble += "#define __weak\n";
6210 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006211
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006212 // Declarations required for modern objective-c array and dictionary literals.
6213 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006214 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006215 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006216 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006217 Preamble += "\tva_list marker;\n";
6218 Preamble += "\tva_start(marker, count);\n";
6219 Preamble += "\tarr = new void *[count];\n";
6220 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6221 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6222 Preamble += "\tva_end( marker );\n";
6223 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006224 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006225 Preamble += "\tdelete[] arr;\n";
6226 Preamble += " }\n";
6227 Preamble += "};\n";
6228
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006229 // Declaration required for implementation of @autoreleasepool statement.
6230 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6231 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6232 Preamble += "struct __AtAutoreleasePool {\n";
6233 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6234 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6235 Preamble += " void * atautoreleasepoolobj;\n";
6236 Preamble += "};\n";
6237
Fariborz Jahanian11671902012-02-07 17:11:38 +00006238 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6239 // as this avoids warning in any 64bit/32bit compilation model.
6240 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6241}
6242
6243/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6244/// ivar offset.
6245void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6246 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006247 Result += "__OFFSETOFIVAR__(struct ";
6248 Result += ivar->getContainingInterface()->getNameAsString();
6249 if (LangOpts.MicrosoftExt)
6250 Result += "_IMPL";
6251 Result += ", ";
6252 if (ivar->isBitField())
6253 ObjCIvarBitfieldGroupDecl(ivar, Result);
6254 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006255 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006256 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006257}
6258
6259/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6260/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006261/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006262/// char *attributes;
6263/// }
6264
6265/// struct _prop_list_t {
6266/// uint32_t entsize; // sizeof(struct _prop_t)
6267/// uint32_t count_of_properties;
6268/// struct _prop_t prop_list[count_of_properties];
6269/// }
6270
6271/// struct _protocol_t;
6272
6273/// struct _protocol_list_t {
6274/// long protocol_count; // Note, this is 32/64 bit
6275/// struct _protocol_t * protocol_list[protocol_count];
6276/// }
6277
6278/// struct _objc_method {
6279/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006280/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006281/// char *_imp;
6282/// }
6283
6284/// struct _method_list_t {
6285/// uint32_t entsize; // sizeof(struct _objc_method)
6286/// uint32_t method_count;
6287/// struct _objc_method method_list[method_count];
6288/// }
6289
6290/// struct _protocol_t {
6291/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006292/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006293/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006294/// const struct method_list_t *instance_methods;
6295/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006296/// const struct method_list_t *optionalInstanceMethods;
6297/// const struct method_list_t *optionalClassMethods;
6298/// const struct _prop_list_t * properties;
6299/// const uint32_t size; // sizeof(struct _protocol_t)
6300/// const uint32_t flags; // = 0
6301/// const char ** extendedMethodTypes;
6302/// }
6303
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006304/// struct _ivar_t {
6305/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006306/// const char *name;
6307/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006308/// uint32_t alignment;
6309/// uint32_t size;
6310/// }
6311
6312/// struct _ivar_list_t {
6313/// uint32 entsize; // sizeof(struct _ivar_t)
6314/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006315/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006316/// }
6317
6318/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006319/// uint32_t flags;
6320/// uint32_t instanceStart;
6321/// uint32_t instanceSize;
6322/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006323/// const uint8_t *ivarLayout;
6324/// const char *name;
6325/// const struct _method_list_t *baseMethods;
6326/// const struct _protocol_list_t *baseProtocols;
6327/// const struct _ivar_list_t *ivars;
6328/// const uint8_t *weakIvarLayout;
6329/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006330/// }
6331
6332/// struct _class_t {
6333/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006334/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006335/// void *cache;
6336/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006337/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006338/// }
6339
6340/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006341/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006342/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006343/// const struct _method_list_t *instance_methods;
6344/// const struct _method_list_t *class_methods;
6345/// const struct _protocol_list_t *protocols;
6346/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006347/// }
6348
6349/// MessageRefTy - LLVM for:
6350/// struct _message_ref_t {
6351/// IMP messenger;
6352/// SEL name;
6353/// };
6354
6355/// SuperMessageRefTy - LLVM for:
6356/// struct _super_message_ref_t {
6357/// SUPER_IMP messenger;
6358/// SEL name;
6359/// };
6360
Fariborz Jahanian45489622012-03-14 18:09:23 +00006361static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006362 static bool meta_data_declared = false;
6363 if (meta_data_declared)
6364 return;
6365
6366 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006367 Result += "\tconst char *name;\n";
6368 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006369 Result += "};\n";
6370
6371 Result += "\nstruct _protocol_t;\n";
6372
Fariborz Jahanian11671902012-02-07 17:11:38 +00006373 Result += "\nstruct _objc_method {\n";
6374 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006375 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006376 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006377 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006378
6379 Result += "\nstruct _protocol_t {\n";
6380 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006381 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006382 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006383 Result += "\tconst struct method_list_t *instance_methods;\n";
6384 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006385 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6386 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6387 Result += "\tconst struct _prop_list_t * properties;\n";
6388 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6389 Result += "\tconst unsigned int flags; // = 0\n";
6390 Result += "\tconst char ** extendedMethodTypes;\n";
6391 Result += "};\n";
6392
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006393 Result += "\nstruct _ivar_t {\n";
6394 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006395 Result += "\tconst char *name;\n";
6396 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006397 Result += "\tunsigned int alignment;\n";
6398 Result += "\tunsigned int size;\n";
6399 Result += "};\n";
6400
6401 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006402 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006403 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006404 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006405 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6406 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006407 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006408 Result += "\tconst unsigned char *ivarLayout;\n";
6409 Result += "\tconst char *name;\n";
6410 Result += "\tconst struct _method_list_t *baseMethods;\n";
6411 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6412 Result += "\tconst struct _ivar_list_t *ivars;\n";
6413 Result += "\tconst unsigned char *weakIvarLayout;\n";
6414 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006415 Result += "};\n";
6416
6417 Result += "\nstruct _class_t {\n";
6418 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006419 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006420 Result += "\tvoid *cache;\n";
6421 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006422 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006423 Result += "};\n";
6424
6425 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006426 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006427 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006428 Result += "\tconst struct _method_list_t *instance_methods;\n";
6429 Result += "\tconst struct _method_list_t *class_methods;\n";
6430 Result += "\tconst struct _protocol_list_t *protocols;\n";
6431 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006432 Result += "};\n";
6433
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006434 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006435 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006436 meta_data_declared = true;
6437}
6438
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006439static void Write_protocol_list_t_TypeDecl(std::string &Result,
6440 long super_protocol_count) {
6441 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6442 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6443 Result += "\tstruct _protocol_t *super_protocols[";
6444 Result += utostr(super_protocol_count); Result += "];\n";
6445 Result += "}";
6446}
6447
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006448static void Write_method_list_t_TypeDecl(std::string &Result,
6449 unsigned int method_count) {
6450 Result += "struct /*_method_list_t*/"; Result += " {\n";
6451 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6452 Result += "\tunsigned int method_count;\n";
6453 Result += "\tstruct _objc_method method_list[";
6454 Result += utostr(method_count); Result += "];\n";
6455 Result += "}";
6456}
6457
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006458static void Write__prop_list_t_TypeDecl(std::string &Result,
6459 unsigned int property_count) {
6460 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6461 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6462 Result += "\tunsigned int count_of_properties;\n";
6463 Result += "\tstruct _prop_t prop_list[";
6464 Result += utostr(property_count); Result += "];\n";
6465 Result += "}";
6466}
6467
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006468static void Write__ivar_list_t_TypeDecl(std::string &Result,
6469 unsigned int ivar_count) {
6470 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6471 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6472 Result += "\tunsigned int count;\n";
6473 Result += "\tstruct _ivar_t ivar_list[";
6474 Result += utostr(ivar_count); Result += "];\n";
6475 Result += "}";
6476}
6477
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006478static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6479 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6480 StringRef VarName,
6481 StringRef ProtocolName) {
6482 if (SuperProtocols.size() > 0) {
6483 Result += "\nstatic ";
6484 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6485 Result += " "; Result += VarName;
6486 Result += ProtocolName;
6487 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6488 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6489 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6490 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6491 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6492 Result += SuperPD->getNameAsString();
6493 if (i == e-1)
6494 Result += "\n};\n";
6495 else
6496 Result += ",\n";
6497 }
6498 }
6499}
6500
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006501static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6502 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006503 ArrayRef<ObjCMethodDecl *> Methods,
6504 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006505 StringRef TopLevelDeclName,
6506 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006507 if (Methods.size() > 0) {
6508 Result += "\nstatic ";
6509 Write_method_list_t_TypeDecl(Result, Methods.size());
6510 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006511 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006512 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6513 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6514 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6515 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6516 ObjCMethodDecl *MD = Methods[i];
6517 if (i == 0)
6518 Result += "\t{{(struct objc_selector *)\"";
6519 else
6520 Result += "\t{(struct objc_selector *)\"";
6521 Result += (MD)->getSelector().getAsString(); Result += "\"";
6522 Result += ", ";
6523 std::string MethodTypeString;
6524 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6525 Result += "\""; Result += MethodTypeString; Result += "\"";
6526 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006527 if (!MethodImpl)
6528 Result += "0";
6529 else {
6530 Result += "(void *)";
6531 Result += RewriteObj.MethodInternalNames[MD];
6532 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006533 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006534 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006535 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006536 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006537 }
6538 Result += "};\n";
6539 }
6540}
6541
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006542static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006543 ASTContext *Context, std::string &Result,
6544 ArrayRef<ObjCPropertyDecl *> Properties,
6545 const Decl *Container,
6546 StringRef VarName,
6547 StringRef ProtocolName) {
6548 if (Properties.size() > 0) {
6549 Result += "\nstatic ";
6550 Write__prop_list_t_TypeDecl(Result, Properties.size());
6551 Result += " "; Result += VarName;
6552 Result += ProtocolName;
6553 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6554 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6555 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6556 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6557 ObjCPropertyDecl *PropDecl = Properties[i];
6558 if (i == 0)
6559 Result += "\t{{\"";
6560 else
6561 Result += "\t{\"";
6562 Result += PropDecl->getName(); Result += "\",";
6563 std::string PropertyTypeString, QuotePropertyTypeString;
6564 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6565 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6566 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6567 if (i == e-1)
6568 Result += "}}\n";
6569 else
6570 Result += "},\n";
6571 }
6572 Result += "};\n";
6573 }
6574}
6575
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006576// Metadata flags
6577enum MetaDataDlags {
6578 CLS = 0x0,
6579 CLS_META = 0x1,
6580 CLS_ROOT = 0x2,
6581 OBJC2_CLS_HIDDEN = 0x10,
6582 CLS_EXCEPTION = 0x20,
6583
6584 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6585 CLS_HAS_IVAR_RELEASER = 0x40,
6586 /// class was compiled with -fobjc-arr
6587 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6588};
6589
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006590static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6591 unsigned int flags,
6592 const std::string &InstanceStart,
6593 const std::string &InstanceSize,
6594 ArrayRef<ObjCMethodDecl *>baseMethods,
6595 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6596 ArrayRef<ObjCIvarDecl *>ivars,
6597 ArrayRef<ObjCPropertyDecl *>Properties,
6598 StringRef VarName,
6599 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006600 Result += "\nstatic struct _class_ro_t ";
6601 Result += VarName; Result += ClassName;
6602 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6603 Result += "\t";
6604 Result += llvm::utostr(flags); Result += ", ";
6605 Result += InstanceStart; Result += ", ";
6606 Result += InstanceSize; Result += ", \n";
6607 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006608 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6609 if (Triple.getArch() == llvm::Triple::x86_64)
6610 // uint32_t const reserved; // only when building for 64bit targets
6611 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006612 // const uint8_t * const ivarLayout;
6613 Result += "0, \n\t";
6614 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006615 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006616 if (baseMethods.size() > 0) {
6617 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006618 if (metaclass)
6619 Result += "_OBJC_$_CLASS_METHODS_";
6620 else
6621 Result += "_OBJC_$_INSTANCE_METHODS_";
6622 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006623 Result += ",\n\t";
6624 }
6625 else
6626 Result += "0, \n\t";
6627
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006628 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006629 Result += "(const struct _objc_protocol_list *)&";
6630 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6631 Result += ",\n\t";
6632 }
6633 else
6634 Result += "0, \n\t";
6635
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006636 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006637 Result += "(const struct _ivar_list_t *)&";
6638 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6639 Result += ",\n\t";
6640 }
6641 else
6642 Result += "0, \n\t";
6643
6644 // weakIvarLayout
6645 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006646 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006647 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006648 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006649 Result += ",\n";
6650 }
6651 else
6652 Result += "0, \n";
6653
6654 Result += "};\n";
6655}
6656
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006657static void Write_class_t(ASTContext *Context, std::string &Result,
6658 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006659 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6660 bool rootClass = (!CDecl->getSuperClass());
6661 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006662
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006663 if (!rootClass) {
6664 // Find the Root class
6665 RootClass = CDecl->getSuperClass();
6666 while (RootClass->getSuperClass()) {
6667 RootClass = RootClass->getSuperClass();
6668 }
6669 }
6670
6671 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006672 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006673 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006674 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006675 if (CDecl->getImplementation())
6676 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006677 else
6678 Result += "__declspec(dllimport) ";
6679
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006680 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006681 Result += CDecl->getNameAsString();
6682 Result += ";\n";
6683 }
6684 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006685 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006686 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006687 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006688 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006689 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006690 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006691 else
6692 Result += "__declspec(dllimport) ";
6693
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006694 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006695 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006696 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006697 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006698
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006699 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006700 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006701 if (RootClass->getImplementation())
6702 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006703 else
6704 Result += "__declspec(dllimport) ";
6705
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006706 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006707 Result += VarName;
6708 Result += RootClass->getNameAsString();
6709 Result += ";\n";
6710 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006711 }
6712
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006713 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6714 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006715 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6716 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006717 if (metaclass) {
6718 if (!rootClass) {
6719 Result += "0, // &"; Result += VarName;
6720 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006721 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006722 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006723 Result += CDecl->getSuperClass()->getNameAsString();
6724 Result += ",\n\t";
6725 }
6726 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006727 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006728 Result += CDecl->getNameAsString();
6729 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006730 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006731 Result += ",\n\t";
6732 }
6733 }
6734 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006735 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006736 Result += CDecl->getNameAsString();
6737 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006738 if (!rootClass) {
6739 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006740 Result += CDecl->getSuperClass()->getNameAsString();
6741 Result += ",\n\t";
6742 }
6743 else
6744 Result += "0,\n\t";
6745 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006746 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6747 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6748 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006749 Result += "&_OBJC_METACLASS_RO_$_";
6750 else
6751 Result += "&_OBJC_CLASS_RO_$_";
6752 Result += CDecl->getNameAsString();
6753 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006754
6755 // Add static function to initialize some of the meta-data fields.
6756 // avoid doing it twice.
6757 if (metaclass)
6758 return;
6759
6760 const ObjCInterfaceDecl *SuperClass =
6761 rootClass ? CDecl : CDecl->getSuperClass();
6762
6763 Result += "static void OBJC_CLASS_SETUP_$_";
6764 Result += CDecl->getNameAsString();
6765 Result += "(void ) {\n";
6766 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6767 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006768 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006769
6770 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006771 Result += ".superclass = ";
6772 if (rootClass)
6773 Result += "&OBJC_CLASS_$_";
6774 else
6775 Result += "&OBJC_METACLASS_$_";
6776
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006777 Result += SuperClass->getNameAsString(); Result += ";\n";
6778
6779 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6780 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6781
6782 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6783 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6784 Result += CDecl->getNameAsString(); Result += ";\n";
6785
6786 if (!rootClass) {
6787 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6788 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6789 Result += SuperClass->getNameAsString(); Result += ";\n";
6790 }
6791
6792 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6793 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6794 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006795}
6796
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006797static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6798 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006799 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006800 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006801 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6802 ArrayRef<ObjCMethodDecl *> ClassMethods,
6803 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6804 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006805 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006806 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006807 // must declare an extern class object in case this class is not implemented
6808 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006809 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006810 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006811 if (ClassDecl->getImplementation())
6812 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006813 else
6814 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006815
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006816 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006817 Result += "OBJC_CLASS_$_"; Result += ClassName;
6818 Result += ";\n";
6819
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006820 Result += "\nstatic struct _category_t ";
6821 Result += "_OBJC_$_CATEGORY_";
6822 Result += ClassName; Result += "_$_"; Result += CatName;
6823 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6824 Result += "{\n";
6825 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006826 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006827 Result += ",\n";
6828 if (InstanceMethods.size() > 0) {
6829 Result += "\t(const struct _method_list_t *)&";
6830 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6831 Result += ClassName; Result += "_$_"; Result += CatName;
6832 Result += ",\n";
6833 }
6834 else
6835 Result += "\t0,\n";
6836
6837 if (ClassMethods.size() > 0) {
6838 Result += "\t(const struct _method_list_t *)&";
6839 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6840 Result += ClassName; Result += "_$_"; Result += CatName;
6841 Result += ",\n";
6842 }
6843 else
6844 Result += "\t0,\n";
6845
6846 if (RefedProtocols.size() > 0) {
6847 Result += "\t(const struct _protocol_list_t *)&";
6848 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6849 Result += ClassName; Result += "_$_"; Result += CatName;
6850 Result += ",\n";
6851 }
6852 else
6853 Result += "\t0,\n";
6854
6855 if (ClassProperties.size() > 0) {
6856 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6857 Result += ClassName; Result += "_$_"; Result += CatName;
6858 Result += ",\n";
6859 }
6860 else
6861 Result += "\t0,\n";
6862
6863 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006864
6865 // Add static function to initialize the class pointer in the category structure.
6866 Result += "static void OBJC_CATEGORY_SETUP_$_";
6867 Result += ClassDecl->getNameAsString();
6868 Result += "_$_";
6869 Result += CatName;
6870 Result += "(void ) {\n";
6871 Result += "\t_OBJC_$_CATEGORY_";
6872 Result += ClassDecl->getNameAsString();
6873 Result += "_$_";
6874 Result += CatName;
6875 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6876 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006877}
6878
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006879static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6880 ASTContext *Context, std::string &Result,
6881 ArrayRef<ObjCMethodDecl *> Methods,
6882 StringRef VarName,
6883 StringRef ProtocolName) {
6884 if (Methods.size() == 0)
6885 return;
6886
6887 Result += "\nstatic const char *";
6888 Result += VarName; Result += ProtocolName;
6889 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6890 Result += "{\n";
6891 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6892 ObjCMethodDecl *MD = Methods[i];
6893 std::string MethodTypeString, QuoteMethodTypeString;
6894 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6895 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6896 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6897 if (i == e-1)
6898 Result += "\n};\n";
6899 else {
6900 Result += ",\n";
6901 }
6902 }
6903}
6904
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006905static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6906 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006907 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006908 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006909 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006910 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6911 // this is what happens:
6912 /**
6913 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6914 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6915 Class->getVisibility() == HiddenVisibility)
6916 Visibility shoud be: HiddenVisibility;
6917 else
6918 Visibility shoud be: DefaultVisibility;
6919 */
6920
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006921 Result += "\n";
6922 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6923 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006924 if (Context->getLangOpts().MicrosoftExt)
6925 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6926
6927 if (!Context->getLangOpts().MicrosoftExt ||
6928 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006929 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006930 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006931 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006932 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006933 if (Ivars[i]->isBitField())
6934 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6935 else
6936 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006937 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6938 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006939 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6940 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006941 if (Ivars[i]->isBitField()) {
6942 // skip over rest of the ivar bitfields.
6943 SKIP_BITFIELDS(i , e, Ivars);
6944 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006945 }
6946}
6947
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006948static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6949 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006950 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006951 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006952 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006953 if (OriginalIvars.size() > 0) {
6954 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6955 SmallVector<ObjCIvarDecl *, 8> Ivars;
6956 // strip off all but the first ivar bitfield from each group of ivars.
6957 // Such ivars in the ivar list table will be replaced by their grouping struct
6958 // 'ivar'.
6959 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6960 if (OriginalIvars[i]->isBitField()) {
6961 Ivars.push_back(OriginalIvars[i]);
6962 // skip over rest of the ivar bitfields.
6963 SKIP_BITFIELDS(i , e, OriginalIvars);
6964 }
6965 else
6966 Ivars.push_back(OriginalIvars[i]);
6967 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006968
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006969 Result += "\nstatic ";
6970 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6971 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006972 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006973 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6974 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6975 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6976 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6977 ObjCIvarDecl *IvarDecl = Ivars[i];
6978 if (i == 0)
6979 Result += "\t{{";
6980 else
6981 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006982 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006983 if (Ivars[i]->isBitField())
6984 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6985 else
6986 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006987 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006988
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006989 Result += "\"";
6990 if (Ivars[i]->isBitField())
6991 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6992 else
6993 Result += IvarDecl->getName();
6994 Result += "\", ";
6995
6996 QualType IVQT = IvarDecl->getType();
6997 if (IvarDecl->isBitField())
6998 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6999
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007000 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007001 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007002 IvarDecl);
7003 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7004 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7005
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007006 // FIXME. this alignment represents the host alignment and need be changed to
7007 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007008 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007009 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007010 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007011 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00007012 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007013 if (i == e-1)
7014 Result += "}}\n";
7015 else
7016 Result += "},\n";
7017 }
7018 Result += "};\n";
7019 }
7020}
7021
Fariborz Jahanian11671902012-02-07 17:11:38 +00007022/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007023void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7024 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007025
Fariborz Jahanian11671902012-02-07 17:11:38 +00007026 // Do not synthesize the protocol more than once.
7027 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7028 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007029 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007030
7031 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7032 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007033 // Must write out all protocol definitions in current qualifier list,
7034 // and in their nested qualifiers before writing out current definition.
7035 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7036 E = PDecl->protocol_end(); I != E; ++I)
7037 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007038
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007039 // Construct method lists.
7040 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7041 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7042 for (ObjCProtocolDecl::instmeth_iterator
7043 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7044 I != E; ++I) {
7045 ObjCMethodDecl *MD = *I;
7046 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7047 OptInstanceMethods.push_back(MD);
7048 } else {
7049 InstanceMethods.push_back(MD);
7050 }
7051 }
7052
7053 for (ObjCProtocolDecl::classmeth_iterator
7054 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7055 I != E; ++I) {
7056 ObjCMethodDecl *MD = *I;
7057 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7058 OptClassMethods.push_back(MD);
7059 } else {
7060 ClassMethods.push_back(MD);
7061 }
7062 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007063 std::vector<ObjCMethodDecl *> AllMethods;
7064 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7065 AllMethods.push_back(InstanceMethods[i]);
7066 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7067 AllMethods.push_back(ClassMethods[i]);
7068 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7069 AllMethods.push_back(OptInstanceMethods[i]);
7070 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7071 AllMethods.push_back(OptClassMethods[i]);
7072
7073 Write__extendedMethodTypes_initializer(*this, Context, Result,
7074 AllMethods,
7075 "_OBJC_PROTOCOL_METHOD_TYPES_",
7076 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007077 // Protocol's super protocol list
7078 std::vector<ObjCProtocolDecl *> SuperProtocols;
7079 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7080 E = PDecl->protocol_end(); I != E; ++I)
7081 SuperProtocols.push_back(*I);
7082
7083 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7084 "_OBJC_PROTOCOL_REFS_",
7085 PDecl->getNameAsString());
7086
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007087 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007088 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007089 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007090
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007091 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007092 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007093 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007094
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007095 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007096 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007097 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007098
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007099 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007100 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007101 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007102
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007103 // Protocol's property metadata.
7104 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7105 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7106 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007107 ProtocolProperties.push_back(*I);
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007108
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007109 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007110 /* Container */0,
7111 "_OBJC_PROTOCOL_PROPERTIES_",
7112 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007113
Fariborz Jahanian48985802012-02-08 00:50:52 +00007114 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007115 Result += "\n";
7116 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007117 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007118 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007119 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007120 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7121 Result += "\t0,\n"; // id is; is null
7122 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007123 if (SuperProtocols.size() > 0) {
7124 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7125 Result += PDecl->getNameAsString(); Result += ",\n";
7126 }
7127 else
7128 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007129 if (InstanceMethods.size() > 0) {
7130 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7131 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007132 }
7133 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007134 Result += "\t0,\n";
7135
7136 if (ClassMethods.size() > 0) {
7137 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7138 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007139 }
7140 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007141 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007142
Fariborz Jahanian48985802012-02-08 00:50:52 +00007143 if (OptInstanceMethods.size() > 0) {
7144 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7145 Result += PDecl->getNameAsString(); Result += ",\n";
7146 }
7147 else
7148 Result += "\t0,\n";
7149
7150 if (OptClassMethods.size() > 0) {
7151 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7152 Result += PDecl->getNameAsString(); Result += ",\n";
7153 }
7154 else
7155 Result += "\t0,\n";
7156
7157 if (ProtocolProperties.size() > 0) {
7158 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7159 Result += PDecl->getNameAsString(); Result += ",\n";
7160 }
7161 else
7162 Result += "\t0,\n";
7163
7164 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7165 Result += "\t0,\n";
7166
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007167 if (AllMethods.size() > 0) {
7168 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7169 Result += PDecl->getNameAsString();
7170 Result += "\n};\n";
7171 }
7172 else
7173 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007174
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007175 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007176 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007177 Result += "struct _protocol_t *";
7178 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7179 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7180 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007181
Fariborz Jahanian11671902012-02-07 17:11:38 +00007182 // Mark this protocol as having been generated.
7183 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7184 llvm_unreachable("protocol already synthesized");
7185
7186}
7187
7188void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7189 const ObjCList<ObjCProtocolDecl> &Protocols,
7190 StringRef prefix, StringRef ClassName,
7191 std::string &Result) {
7192 if (Protocols.empty()) return;
7193
7194 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007195 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007196
7197 // Output the top lovel protocol meta-data for the class.
7198 /* struct _objc_protocol_list {
7199 struct _objc_protocol_list *next;
7200 int protocol_count;
7201 struct _objc_protocol *class_protocols[];
7202 }
7203 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007204 Result += "\n";
7205 if (LangOpts.MicrosoftExt)
7206 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7207 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007208 Result += "\tstruct _objc_protocol_list *next;\n";
7209 Result += "\tint protocol_count;\n";
7210 Result += "\tstruct _objc_protocol *class_protocols[";
7211 Result += utostr(Protocols.size());
7212 Result += "];\n} _OBJC_";
7213 Result += prefix;
7214 Result += "_PROTOCOLS_";
7215 Result += ClassName;
7216 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7217 "{\n\t0, ";
7218 Result += utostr(Protocols.size());
7219 Result += "\n";
7220
7221 Result += "\t,{&_OBJC_PROTOCOL_";
7222 Result += Protocols[0]->getNameAsString();
7223 Result += " \n";
7224
7225 for (unsigned i = 1; i != Protocols.size(); i++) {
7226 Result += "\t ,&_OBJC_PROTOCOL_";
7227 Result += Protocols[i]->getNameAsString();
7228 Result += "\n";
7229 }
7230 Result += "\t }\n};\n";
7231}
7232
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007233/// hasObjCExceptionAttribute - Return true if this class or any super
7234/// class has the __objc_exception__ attribute.
7235/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7236static bool hasObjCExceptionAttribute(ASTContext &Context,
7237 const ObjCInterfaceDecl *OID) {
7238 if (OID->hasAttr<ObjCExceptionAttr>())
7239 return true;
7240 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7241 return hasObjCExceptionAttribute(Context, Super);
7242 return false;
7243}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007244
Fariborz Jahanian11671902012-02-07 17:11:38 +00007245void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7246 std::string &Result) {
7247 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7248
7249 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007250 if (CDecl->isImplicitInterfaceDecl())
7251 assert(false &&
7252 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007253
Fariborz Jahanian45489622012-03-14 18:09:23 +00007254 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007255 SmallVector<ObjCIvarDecl *, 8> IVars;
7256
7257 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7258 IVD; IVD = IVD->getNextIvar()) {
7259 // Ignore unnamed bit-fields.
7260 if (!IVD->getDeclName())
7261 continue;
7262 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007263 }
7264
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007265 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007266 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007267 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007268
7269 // Build _objc_method_list for class's instance methods if needed
7270 SmallVector<ObjCMethodDecl *, 32>
7271 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7272
7273 // If any of our property implementations have associated getters or
7274 // setters, produce metadata for them as well.
7275 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7276 PropEnd = IDecl->propimpl_end();
7277 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007278 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007279 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007280 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007281 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007282 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007283 if (!PD)
7284 continue;
7285 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007286 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007287 InstanceMethods.push_back(Getter);
7288 if (PD->isReadOnly())
7289 continue;
7290 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007291 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007292 InstanceMethods.push_back(Setter);
7293 }
7294
7295 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7296 "_OBJC_$_INSTANCE_METHODS_",
7297 IDecl->getNameAsString(), true);
7298
7299 SmallVector<ObjCMethodDecl *, 32>
7300 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7301
7302 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7303 "_OBJC_$_CLASS_METHODS_",
7304 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007305
7306 // Protocols referenced in class declaration?
7307 // Protocol's super protocol list
7308 std::vector<ObjCProtocolDecl *> RefedProtocols;
7309 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7310 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7311 E = Protocols.end();
7312 I != E; ++I) {
7313 RefedProtocols.push_back(*I);
7314 // Must write out all protocol definitions in current qualifier list,
7315 // and in their nested qualifiers before writing out current definition.
7316 RewriteObjCProtocolMetaData(*I, Result);
7317 }
7318
7319 Write_protocol_list_initializer(Context, Result,
7320 RefedProtocols,
7321 "_OBJC_CLASS_PROTOCOLS_$_",
7322 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007323
7324 // Protocol's property metadata.
7325 std::vector<ObjCPropertyDecl *> ClassProperties;
7326 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7327 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007328 ClassProperties.push_back(*I);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007329
7330 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007331 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007332 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007333 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007334
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007335
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007336 // Data for initializing _class_ro_t metaclass meta-data
7337 uint32_t flags = CLS_META;
7338 std::string InstanceSize;
7339 std::string InstanceStart;
7340
7341
7342 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7343 if (classIsHidden)
7344 flags |= OBJC2_CLS_HIDDEN;
7345
7346 if (!CDecl->getSuperClass())
7347 // class is root
7348 flags |= CLS_ROOT;
7349 InstanceSize = "sizeof(struct _class_t)";
7350 InstanceStart = InstanceSize;
7351 Write__class_ro_t_initializer(Context, Result, flags,
7352 InstanceStart, InstanceSize,
7353 ClassMethods,
7354 0,
7355 0,
7356 0,
7357 "_OBJC_METACLASS_RO_$_",
7358 CDecl->getNameAsString());
7359
7360
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007361 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007362 flags = CLS;
7363 if (classIsHidden)
7364 flags |= OBJC2_CLS_HIDDEN;
7365
7366 if (hasObjCExceptionAttribute(*Context, CDecl))
7367 flags |= CLS_EXCEPTION;
7368
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007369 if (!CDecl->getSuperClass())
7370 // class is root
7371 flags |= CLS_ROOT;
7372
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007373 InstanceSize.clear();
7374 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007375 if (!ObjCSynthesizedStructs.count(CDecl)) {
7376 InstanceSize = "0";
7377 InstanceStart = "0";
7378 }
7379 else {
7380 InstanceSize = "sizeof(struct ";
7381 InstanceSize += CDecl->getNameAsString();
7382 InstanceSize += "_IMPL)";
7383
7384 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7385 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007386 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007387 }
7388 else
7389 InstanceStart = InstanceSize;
7390 }
7391 Write__class_ro_t_initializer(Context, Result, flags,
7392 InstanceStart, InstanceSize,
7393 InstanceMethods,
7394 RefedProtocols,
7395 IVars,
7396 ClassProperties,
7397 "_OBJC_CLASS_RO_$_",
7398 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007399
7400 Write_class_t(Context, Result,
7401 "OBJC_METACLASS_$_",
7402 CDecl, /*metaclass*/true);
7403
7404 Write_class_t(Context, Result,
7405 "OBJC_CLASS_$_",
7406 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007407
7408 if (ImplementationIsNonLazy(IDecl))
7409 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007410
Fariborz Jahanian11671902012-02-07 17:11:38 +00007411}
7412
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007413void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7414 int ClsDefCount = ClassImplementation.size();
7415 if (!ClsDefCount)
7416 return;
7417 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7418 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7419 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7420 for (int i = 0; i < ClsDefCount; i++) {
7421 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7422 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7423 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7424 Result += CDecl->getName(); Result += ",\n";
7425 }
7426 Result += "};\n";
7427}
7428
Fariborz Jahanian11671902012-02-07 17:11:38 +00007429void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7430 int ClsDefCount = ClassImplementation.size();
7431 int CatDefCount = CategoryImplementation.size();
7432
7433 // For each implemented class, write out all its meta data.
7434 for (int i = 0; i < ClsDefCount; i++)
7435 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7436
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007437 RewriteClassSetupInitHook(Result);
7438
Fariborz Jahanian11671902012-02-07 17:11:38 +00007439 // For each implemented category, write out all its meta data.
7440 for (int i = 0; i < CatDefCount; i++)
7441 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7442
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007443 RewriteCategorySetupInitHook(Result);
7444
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007445 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007446 if (LangOpts.MicrosoftExt)
7447 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007448 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7449 Result += llvm::utostr(ClsDefCount); Result += "]";
7450 Result +=
7451 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7452 "regular,no_dead_strip\")))= {\n";
7453 for (int i = 0; i < ClsDefCount; i++) {
7454 Result += "\t&OBJC_CLASS_$_";
7455 Result += ClassImplementation[i]->getNameAsString();
7456 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007457 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007458 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007459
7460 if (!DefinedNonLazyClasses.empty()) {
7461 if (LangOpts.MicrosoftExt)
7462 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7463 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7464 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7465 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7466 Result += ",\n";
7467 }
7468 Result += "};\n";
7469 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007470 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007471
7472 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007473 if (LangOpts.MicrosoftExt)
7474 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007475 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7476 Result += llvm::utostr(CatDefCount); Result += "]";
7477 Result +=
7478 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7479 "regular,no_dead_strip\")))= {\n";
7480 for (int i = 0; i < CatDefCount; i++) {
7481 Result += "\t&_OBJC_$_CATEGORY_";
7482 Result +=
7483 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7484 Result += "_$_";
7485 Result += CategoryImplementation[i]->getNameAsString();
7486 Result += ",\n";
7487 }
7488 Result += "};\n";
7489 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007490
7491 if (!DefinedNonLazyCategories.empty()) {
7492 if (LangOpts.MicrosoftExt)
7493 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7494 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7495 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7496 Result += "\t&_OBJC_$_CATEGORY_";
7497 Result +=
7498 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7499 Result += "_$_";
7500 Result += DefinedNonLazyCategories[i]->getNameAsString();
7501 Result += ",\n";
7502 }
7503 Result += "};\n";
7504 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007505}
7506
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007507void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7508 if (LangOpts.MicrosoftExt)
7509 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7510
7511 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7512 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007513 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007514}
7515
Fariborz Jahanian11671902012-02-07 17:11:38 +00007516/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7517/// implementation.
7518void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7519 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007520 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007521 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7522 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007523 ObjCCategoryDecl *CDecl
7524 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007525
7526 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007527 FullCategoryName += "_$_";
7528 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007529
7530 // Build _objc_method_list for class's instance methods if needed
7531 SmallVector<ObjCMethodDecl *, 32>
7532 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7533
7534 // If any of our property implementations have associated getters or
7535 // setters, produce metadata for them as well.
7536 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7537 PropEnd = IDecl->propimpl_end();
7538 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007539 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007540 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007541 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007542 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007543 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007544 if (!PD)
7545 continue;
7546 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7547 InstanceMethods.push_back(Getter);
7548 if (PD->isReadOnly())
7549 continue;
7550 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7551 InstanceMethods.push_back(Setter);
7552 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007553
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007554 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7555 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7556 FullCategoryName, true);
7557
7558 SmallVector<ObjCMethodDecl *, 32>
7559 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7560
7561 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7562 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7563 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007564
7565 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007566 // Protocol's super protocol list
7567 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007568 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7569 E = CDecl->protocol_end();
7570
7571 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007572 RefedProtocols.push_back(*I);
7573 // Must write out all protocol definitions in current qualifier list,
7574 // and in their nested qualifiers before writing out current definition.
7575 RewriteObjCProtocolMetaData(*I, Result);
7576 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007577
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007578 Write_protocol_list_initializer(Context, Result,
7579 RefedProtocols,
7580 "_OBJC_CATEGORY_PROTOCOLS_$_",
7581 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007582
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007583 // Protocol's property metadata.
7584 std::vector<ObjCPropertyDecl *> ClassProperties;
7585 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7586 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007587 ClassProperties.push_back(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007588
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007589 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007590 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007591 "_OBJC_$_PROP_LIST_",
7592 FullCategoryName);
7593
7594 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007595 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007596 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007597 InstanceMethods,
7598 ClassMethods,
7599 RefedProtocols,
7600 ClassProperties);
7601
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007602 // Determine if this category is also "non-lazy".
7603 if (ImplementationIsNonLazy(IDecl))
7604 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007605
7606}
7607
7608void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7609 int CatDefCount = CategoryImplementation.size();
7610 if (!CatDefCount)
7611 return;
7612 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7613 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7614 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7615 for (int i = 0; i < CatDefCount; i++) {
7616 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7617 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7618 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7619 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7620 Result += ClassDecl->getName();
7621 Result += "_$_";
7622 Result += CatDecl->getName();
7623 Result += ",\n";
7624 }
7625 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007626}
7627
7628// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7629/// class methods.
7630template<typename MethodIterator>
7631void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7632 MethodIterator MethodEnd,
7633 bool IsInstanceMethod,
7634 StringRef prefix,
7635 StringRef ClassName,
7636 std::string &Result) {
7637 if (MethodBegin == MethodEnd) return;
7638
7639 if (!objc_impl_method) {
7640 /* struct _objc_method {
7641 SEL _cmd;
7642 char *method_types;
7643 void *_imp;
7644 }
7645 */
7646 Result += "\nstruct _objc_method {\n";
7647 Result += "\tSEL _cmd;\n";
7648 Result += "\tchar *method_types;\n";
7649 Result += "\tvoid *_imp;\n";
7650 Result += "};\n";
7651
7652 objc_impl_method = true;
7653 }
7654
7655 // Build _objc_method_list for class's methods if needed
7656
7657 /* struct {
7658 struct _objc_method_list *next_method;
7659 int method_count;
7660 struct _objc_method method_list[];
7661 }
7662 */
7663 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007664 Result += "\n";
7665 if (LangOpts.MicrosoftExt) {
7666 if (IsInstanceMethod)
7667 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7668 else
7669 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7670 }
7671 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007672 Result += "\tstruct _objc_method_list *next_method;\n";
7673 Result += "\tint method_count;\n";
7674 Result += "\tstruct _objc_method method_list[";
7675 Result += utostr(NumMethods);
7676 Result += "];\n} _OBJC_";
7677 Result += prefix;
7678 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7679 Result += "_METHODS_";
7680 Result += ClassName;
7681 Result += " __attribute__ ((used, section (\"__OBJC, __";
7682 Result += IsInstanceMethod ? "inst" : "cls";
7683 Result += "_meth\")))= ";
7684 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7685
7686 Result += "\t,{{(SEL)\"";
7687 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7688 std::string MethodTypeString;
7689 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7690 Result += "\", \"";
7691 Result += MethodTypeString;
7692 Result += "\", (void *)";
7693 Result += MethodInternalNames[*MethodBegin];
7694 Result += "}\n";
7695 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7696 Result += "\t ,{(SEL)\"";
7697 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7698 std::string MethodTypeString;
7699 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7700 Result += "\", \"";
7701 Result += MethodTypeString;
7702 Result += "\", (void *)";
7703 Result += MethodInternalNames[*MethodBegin];
7704 Result += "}\n";
7705 }
7706 Result += "\t }\n};\n";
7707}
7708
7709Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7710 SourceRange OldRange = IV->getSourceRange();
7711 Expr *BaseExpr = IV->getBase();
7712
7713 // Rewrite the base, but without actually doing replaces.
7714 {
7715 DisableReplaceStmtScope S(*this);
7716 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7717 IV->setBase(BaseExpr);
7718 }
7719
7720 ObjCIvarDecl *D = IV->getDecl();
7721
7722 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007723
Fariborz Jahanian11671902012-02-07 17:11:38 +00007724 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7725 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007726 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007727 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7728 // lookup which class implements the instance variable.
7729 ObjCInterfaceDecl *clsDeclared = 0;
7730 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7731 clsDeclared);
7732 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7733
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007734 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007735 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007736 if (D->isBitField())
7737 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7738 else
7739 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007740
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007741 ReferencedIvars[clsDeclared].insert(D);
7742
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007743 // cast offset to "char *".
7744 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7745 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007746 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007747 BaseExpr);
7748 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7749 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007750 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007751 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7752 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007753 SourceLocation());
7754 BinaryOperator *addExpr =
7755 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7756 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007757 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007758 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007759 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7760 SourceLocation(),
7761 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007762 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007763 if (D->isBitField())
7764 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007765
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007766 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007767 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007768 RD = RD->getDefinition();
7769 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007770 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007771 ObjCContainerDecl *CDecl =
7772 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7773 // ivar in class extensions requires special treatment.
7774 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7775 CDecl = CatDecl->getClassInterface();
7776 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007777 RecName += "_IMPL";
7778 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7779 SourceLocation(), SourceLocation(),
7780 &Context->Idents.get(RecName.c_str()));
7781 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7782 unsigned UnsignedIntSize =
7783 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7784 Expr *Zero = IntegerLiteral::Create(*Context,
7785 llvm::APInt(UnsignedIntSize, 0),
7786 Context->UnsignedIntTy, SourceLocation());
7787 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7788 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7789 Zero);
7790 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7791 SourceLocation(),
7792 &Context->Idents.get(D->getNameAsString()),
7793 IvarT, 0,
7794 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007795 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007796 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7797 FD->getType(), VK_LValue,
7798 OK_Ordinary);
7799 IvarT = Context->getDecltypeType(ME, ME->getType());
7800 }
7801 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007802 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007803 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007804
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007805 castExpr = NoTypeInfoCStyleCastExpr(Context,
7806 castT,
7807 CK_BitCast,
7808 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007809
7810
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007811 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007812 VK_LValue, OK_Ordinary,
7813 SourceLocation());
7814 PE = new (Context) ParenExpr(OldRange.getBegin(),
7815 OldRange.getEnd(),
7816 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007817
7818 if (D->isBitField()) {
7819 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7820 SourceLocation(),
7821 &Context->Idents.get(D->getNameAsString()),
7822 D->getType(), 0,
7823 /*BitWidth=*/D->getBitWidth(),
7824 /*Mutable=*/true,
7825 ICIS_NoInit);
7826 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7827 FD->getType(), VK_LValue,
7828 OK_Ordinary);
7829 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007830
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007831 }
7832 else
7833 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007834 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007835
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007836 ReplaceStmtWithRange(IV, Replacement, OldRange);
7837 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007838}