blob: 312c6ade05a60a1e42ec513e9084760b66fcb245 [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"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
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
Aaron Ballmand174edf2014-03-13 19:11:50 +00001163 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001164 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001165
1166 for (ObjCCategoryDecl::instmeth_iterator
1167 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1168 I != E; ++I)
1169 RewriteMethodDeclaration(*I);
1170 for (ObjCCategoryDecl::classmeth_iterator
1171 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1172 I != E; ++I)
1173 RewriteMethodDeclaration(*I);
1174
1175 // Lastly, comment out the @end.
1176 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001177 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001178}
1179
1180void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1181 SourceLocation LocStart = PDecl->getLocStart();
1182 assert(PDecl->isThisDeclarationADefinition());
1183
1184 // FIXME: handle protocol headers that are declared across multiple lines.
1185 ReplaceText(LocStart, 0, "// ");
1186
1187 for (ObjCProtocolDecl::instmeth_iterator
1188 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1189 I != E; ++I)
1190 RewriteMethodDeclaration(*I);
1191 for (ObjCProtocolDecl::classmeth_iterator
1192 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1193 I != E; ++I)
1194 RewriteMethodDeclaration(*I);
1195
Aaron Ballmand174edf2014-03-13 19:11:50 +00001196 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001197 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001198
1199 // Lastly, comment out the @end.
1200 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001201 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001202
1203 // Must comment out @optional/@required
1204 const char *startBuf = SM->getCharacterData(LocStart);
1205 const char *endBuf = SM->getCharacterData(LocEnd);
1206 for (const char *p = startBuf; p < endBuf; p++) {
1207 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1208 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1209 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1210
1211 }
1212 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1213 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1214 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1215
1216 }
1217 }
1218}
1219
1220void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1221 SourceLocation LocStart = (*D.begin())->getLocStart();
1222 if (LocStart.isInvalid())
1223 llvm_unreachable("Invalid SourceLocation");
1224 // FIXME: handle forward protocol that are declared across multiple lines.
1225 ReplaceText(LocStart, 0, "// ");
1226}
1227
1228void
Craig Topper5603df42013-07-05 19:34:19 +00001229RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001230 SourceLocation LocStart = DG[0]->getLocStart();
1231 if (LocStart.isInvalid())
1232 llvm_unreachable("Invalid SourceLocation");
1233 // FIXME: handle forward protocol that are declared across multiple lines.
1234 ReplaceText(LocStart, 0, "// ");
1235}
1236
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001237void
1238RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1239 SourceLocation LocStart = LSD->getExternLoc();
1240 if (LocStart.isInvalid())
1241 llvm_unreachable("Invalid extern SourceLocation");
1242
1243 ReplaceText(LocStart, 0, "// ");
1244 if (!LSD->hasBraces())
1245 return;
1246 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1247 SourceLocation LocRBrace = LSD->getRBraceLoc();
1248 if (LocRBrace.isInvalid())
1249 llvm_unreachable("Invalid rbrace SourceLocation");
1250 ReplaceText(LocRBrace, 0, "// ");
1251}
1252
Fariborz Jahanian11671902012-02-07 17:11:38 +00001253void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1254 const FunctionType *&FPRetType) {
1255 if (T->isObjCQualifiedIdType())
1256 ResultStr += "id";
1257 else if (T->isFunctionPointerType() ||
1258 T->isBlockPointerType()) {
1259 // needs special handling, since pointer-to-functions have special
1260 // syntax (where a decaration models use).
1261 QualType retType = T;
1262 QualType PointeeTy;
1263 if (const PointerType* PT = retType->getAs<PointerType>())
1264 PointeeTy = PT->getPointeeType();
1265 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1266 PointeeTy = BPT->getPointeeType();
1267 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001268 ResultStr +=
1269 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001270 ResultStr += "(*";
1271 }
1272 } else
1273 ResultStr += T.getAsString(Context->getPrintingPolicy());
1274}
1275
1276void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1277 ObjCMethodDecl *OMD,
1278 std::string &ResultStr) {
1279 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1280 const FunctionType *FPRetType = 0;
1281 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001282 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001283 ResultStr += " ";
1284
1285 // Unique method name
1286 std::string NameStr;
1287
1288 if (OMD->isInstanceMethod())
1289 NameStr += "_I_";
1290 else
1291 NameStr += "_C_";
1292
1293 NameStr += IDecl->getNameAsString();
1294 NameStr += "_";
1295
1296 if (ObjCCategoryImplDecl *CID =
1297 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1298 NameStr += CID->getNameAsString();
1299 NameStr += "_";
1300 }
1301 // Append selector names, replacing ':' with '_'
1302 {
1303 std::string selString = OMD->getSelector().getAsString();
1304 int len = selString.size();
1305 for (int i = 0; i < len; i++)
1306 if (selString[i] == ':')
1307 selString[i] = '_';
1308 NameStr += selString;
1309 }
1310 // Remember this name for metadata emission
1311 MethodInternalNames[OMD] = NameStr;
1312 ResultStr += NameStr;
1313
1314 // Rewrite arguments
1315 ResultStr += "(";
1316
1317 // invisible arguments
1318 if (OMD->isInstanceMethod()) {
1319 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1320 selfTy = Context->getPointerType(selfTy);
1321 if (!LangOpts.MicrosoftExt) {
1322 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1323 ResultStr += "struct ";
1324 }
1325 // When rewriting for Microsoft, explicitly omit the structure name.
1326 ResultStr += IDecl->getNameAsString();
1327 ResultStr += " *";
1328 }
1329 else
1330 ResultStr += Context->getObjCClassType().getAsString(
1331 Context->getPrintingPolicy());
1332
1333 ResultStr += " self, ";
1334 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1335 ResultStr += " _cmd";
1336
1337 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001338 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001339 ResultStr += ", ";
1340 if (PDecl->getType()->isObjCQualifiedIdType()) {
1341 ResultStr += "id ";
1342 ResultStr += PDecl->getNameAsString();
1343 } else {
1344 std::string Name = PDecl->getNameAsString();
1345 QualType QT = PDecl->getType();
1346 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001347 (void)convertBlockPointerToFunctionPointer(QT);
1348 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001349 ResultStr += Name;
1350 }
1351 }
1352 if (OMD->isVariadic())
1353 ResultStr += ", ...";
1354 ResultStr += ") ";
1355
1356 if (FPRetType) {
1357 ResultStr += ")"; // close the precedence "scope" for "*".
1358
1359 // Now, emit the argument types (if any).
1360 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1361 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001362 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001363 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001364 std::string ParamStr =
1365 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001366 ResultStr += ParamStr;
1367 }
1368 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001369 if (FT->getNumParams())
1370 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001371 ResultStr += "...";
1372 }
1373 ResultStr += ")";
1374 } else {
1375 ResultStr += "()";
1376 }
1377 }
1378}
1379void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1380 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1381 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1382
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001383 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001384 if (IMD->getIvarRBraceLoc().isValid()) {
1385 ReplaceText(IMD->getLocStart(), 1, "/** ");
1386 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001387 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001388 else {
1389 InsertText(IMD->getLocStart(), "// ");
1390 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001391 }
1392 else
1393 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001394
1395 for (ObjCCategoryImplDecl::instmeth_iterator
1396 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1397 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1398 I != E; ++I) {
1399 std::string ResultStr;
1400 ObjCMethodDecl *OMD = *I;
1401 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1402 SourceLocation LocStart = OMD->getLocStart();
1403 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1404
1405 const char *startBuf = SM->getCharacterData(LocStart);
1406 const char *endBuf = SM->getCharacterData(LocEnd);
1407 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1408 }
1409
1410 for (ObjCCategoryImplDecl::classmeth_iterator
1411 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1412 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1413 I != E; ++I) {
1414 std::string ResultStr;
1415 ObjCMethodDecl *OMD = *I;
1416 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1417 SourceLocation LocStart = OMD->getLocStart();
1418 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1419
1420 const char *startBuf = SM->getCharacterData(LocStart);
1421 const char *endBuf = SM->getCharacterData(LocEnd);
1422 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1423 }
1424 for (ObjCCategoryImplDecl::propimpl_iterator
1425 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1426 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1427 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001428 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001429 }
1430
1431 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1432}
1433
1434void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001435 // Do not synthesize more than once.
1436 if (ObjCSynthesizedStructs.count(ClassDecl))
1437 return;
1438 // Make sure super class's are written before current class is written.
1439 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1440 while (SuperClass) {
1441 RewriteInterfaceDecl(SuperClass);
1442 SuperClass = SuperClass->getSuperClass();
1443 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001444 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001445 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001446 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001447 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001448 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1449
Fariborz Jahanianff513382012-02-15 22:01:47 +00001450 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001451 // Mark this typedef as having been written into its c++ equivalent.
1452 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001453
Aaron Ballmand174edf2014-03-13 19:11:50 +00001454 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001455 RewriteProperty(I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001456 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001457 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001458 I != E; ++I)
1459 RewriteMethodDeclaration(*I);
1460 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001461 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001462 I != E; ++I)
1463 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001464
Fariborz Jahanianff513382012-02-15 22:01:47 +00001465 // Lastly, comment out the @end.
1466 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001467 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001468 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001469}
1470
1471Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1472 SourceRange OldRange = PseudoOp->getSourceRange();
1473
1474 // We just magically know some things about the structure of this
1475 // expression.
1476 ObjCMessageExpr *OldMsg =
1477 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1478 PseudoOp->getNumSemanticExprs() - 1));
1479
1480 // Because the rewriter doesn't allow us to rewrite rewritten code,
1481 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001482 Expr *Base;
1483 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001484 {
1485 DisableReplaceStmtScope S(*this);
1486
1487 // Rebuild the base expression if we have one.
1488 Base = 0;
1489 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1490 Base = OldMsg->getInstanceReceiver();
1491 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1492 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1493 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001494
1495 unsigned numArgs = OldMsg->getNumArgs();
1496 for (unsigned i = 0; i < numArgs; i++) {
1497 Expr *Arg = OldMsg->getArg(i);
1498 if (isa<OpaqueValueExpr>(Arg))
1499 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1500 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1501 Args.push_back(Arg);
1502 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001503 }
1504
1505 // TODO: avoid this copy.
1506 SmallVector<SourceLocation, 1> SelLocs;
1507 OldMsg->getSelectorLocs(SelLocs);
1508
1509 ObjCMessageExpr *NewMsg = 0;
1510 switch (OldMsg->getReceiverKind()) {
1511 case ObjCMessageExpr::Class:
1512 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1513 OldMsg->getValueKind(),
1514 OldMsg->getLeftLoc(),
1515 OldMsg->getClassReceiverTypeInfo(),
1516 OldMsg->getSelector(),
1517 SelLocs,
1518 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001519 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001520 OldMsg->getRightLoc(),
1521 OldMsg->isImplicit());
1522 break;
1523
1524 case ObjCMessageExpr::Instance:
1525 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1526 OldMsg->getValueKind(),
1527 OldMsg->getLeftLoc(),
1528 Base,
1529 OldMsg->getSelector(),
1530 SelLocs,
1531 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001532 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001533 OldMsg->getRightLoc(),
1534 OldMsg->isImplicit());
1535 break;
1536
1537 case ObjCMessageExpr::SuperClass:
1538 case ObjCMessageExpr::SuperInstance:
1539 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1540 OldMsg->getValueKind(),
1541 OldMsg->getLeftLoc(),
1542 OldMsg->getSuperLoc(),
1543 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1544 OldMsg->getSuperType(),
1545 OldMsg->getSelector(),
1546 SelLocs,
1547 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001548 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001549 OldMsg->getRightLoc(),
1550 OldMsg->isImplicit());
1551 break;
1552 }
1553
1554 Stmt *Replacement = SynthMessageExpr(NewMsg);
1555 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1556 return Replacement;
1557}
1558
1559Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1560 SourceRange OldRange = PseudoOp->getSourceRange();
1561
1562 // We just magically know some things about the structure of this
1563 // expression.
1564 ObjCMessageExpr *OldMsg =
1565 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1566
1567 // Because the rewriter doesn't allow us to rewrite rewritten code,
1568 // we need to suppress rewriting the sub-statements.
1569 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001570 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001571 {
1572 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001573 // Rebuild the base expression if we have one.
1574 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1575 Base = OldMsg->getInstanceReceiver();
1576 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1577 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1578 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001579 unsigned numArgs = OldMsg->getNumArgs();
1580 for (unsigned i = 0; i < numArgs; i++) {
1581 Expr *Arg = OldMsg->getArg(i);
1582 if (isa<OpaqueValueExpr>(Arg))
1583 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1584 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1585 Args.push_back(Arg);
1586 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001587 }
1588
1589 // Intentionally empty.
1590 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001591
1592 ObjCMessageExpr *NewMsg = 0;
1593 switch (OldMsg->getReceiverKind()) {
1594 case ObjCMessageExpr::Class:
1595 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1596 OldMsg->getValueKind(),
1597 OldMsg->getLeftLoc(),
1598 OldMsg->getClassReceiverTypeInfo(),
1599 OldMsg->getSelector(),
1600 SelLocs,
1601 OldMsg->getMethodDecl(),
1602 Args,
1603 OldMsg->getRightLoc(),
1604 OldMsg->isImplicit());
1605 break;
1606
1607 case ObjCMessageExpr::Instance:
1608 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1609 OldMsg->getValueKind(),
1610 OldMsg->getLeftLoc(),
1611 Base,
1612 OldMsg->getSelector(),
1613 SelLocs,
1614 OldMsg->getMethodDecl(),
1615 Args,
1616 OldMsg->getRightLoc(),
1617 OldMsg->isImplicit());
1618 break;
1619
1620 case ObjCMessageExpr::SuperClass:
1621 case ObjCMessageExpr::SuperInstance:
1622 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1623 OldMsg->getValueKind(),
1624 OldMsg->getLeftLoc(),
1625 OldMsg->getSuperLoc(),
1626 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1627 OldMsg->getSuperType(),
1628 OldMsg->getSelector(),
1629 SelLocs,
1630 OldMsg->getMethodDecl(),
1631 Args,
1632 OldMsg->getRightLoc(),
1633 OldMsg->isImplicit());
1634 break;
1635 }
1636
1637 Stmt *Replacement = SynthMessageExpr(NewMsg);
1638 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1639 return Replacement;
1640}
1641
1642/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001643/// ((NSUInteger (*)
1644/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001645/// (void *)objc_msgSend)((id)l_collection,
1646/// sel_registerName(
1647/// "countByEnumeratingWithState:objects:count:"),
1648/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001649/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001650///
1651void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001652 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1653 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001654 buf += "\n\t\t";
1655 buf += "((id)l_collection,\n\t\t";
1656 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1657 buf += "\n\t\t";
1658 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001659 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001660}
1661
1662/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1663/// statement to exit to its outer synthesized loop.
1664///
1665Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1666 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1667 return S;
1668 // replace break with goto __break_label
1669 std::string buf;
1670
1671 SourceLocation startLoc = S->getLocStart();
1672 buf = "goto __break_label_";
1673 buf += utostr(ObjCBcLabelNo.back());
1674 ReplaceText(startLoc, strlen("break"), buf);
1675
1676 return 0;
1677}
1678
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001679void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1680 SourceLocation Loc,
1681 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001682 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001683 LineString += "\n#line ";
1684 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1685 LineString += utostr(PLoc.getLine());
1686 LineString += " \"";
1687 LineString += Lexer::Stringify(PLoc.getFilename());
1688 LineString += "\"\n";
1689 }
1690}
1691
Fariborz Jahanian11671902012-02-07 17:11:38 +00001692/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1693/// statement to continue with its inner synthesized loop.
1694///
1695Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1696 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1697 return S;
1698 // replace continue with goto __continue_label
1699 std::string buf;
1700
1701 SourceLocation startLoc = S->getLocStart();
1702 buf = "goto __continue_label_";
1703 buf += utostr(ObjCBcLabelNo.back());
1704 ReplaceText(startLoc, strlen("continue"), buf);
1705
1706 return 0;
1707}
1708
1709/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1710/// It rewrites:
1711/// for ( type elem in collection) { stmts; }
1712
1713/// Into:
1714/// {
1715/// type elem;
1716/// struct __objcFastEnumerationState enumState = { 0 };
1717/// id __rw_items[16];
1718/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001719/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001720/// objects:__rw_items count:16];
1721/// if (limit) {
1722/// unsigned long startMutations = *enumState.mutationsPtr;
1723/// do {
1724/// unsigned long counter = 0;
1725/// do {
1726/// if (startMutations != *enumState.mutationsPtr)
1727/// objc_enumerationMutation(l_collection);
1728/// elem = (type)enumState.itemsPtr[counter++];
1729/// stmts;
1730/// __continue_label: ;
1731/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001732/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1733/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001734/// elem = nil;
1735/// __break_label: ;
1736/// }
1737/// else
1738/// elem = nil;
1739/// }
1740///
1741Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1742 SourceLocation OrigEnd) {
1743 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1744 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1745 "ObjCForCollectionStmt Statement stack mismatch");
1746 assert(!ObjCBcLabelNo.empty() &&
1747 "ObjCForCollectionStmt - Label No stack empty");
1748
1749 SourceLocation startLoc = S->getLocStart();
1750 const char *startBuf = SM->getCharacterData(startLoc);
1751 StringRef elementName;
1752 std::string elementTypeAsString;
1753 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001754 // line directive first.
1755 SourceLocation ForEachLoc = S->getForLoc();
1756 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1757 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001758 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1759 // type elem;
1760 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1761 QualType ElementType = cast<ValueDecl>(D)->getType();
1762 if (ElementType->isObjCQualifiedIdType() ||
1763 ElementType->isObjCQualifiedInterfaceType())
1764 // Simply use 'id' for all qualified types.
1765 elementTypeAsString = "id";
1766 else
1767 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1768 buf += elementTypeAsString;
1769 buf += " ";
1770 elementName = D->getName();
1771 buf += elementName;
1772 buf += ";\n\t";
1773 }
1774 else {
1775 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1776 elementName = DR->getDecl()->getName();
1777 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1778 if (VD->getType()->isObjCQualifiedIdType() ||
1779 VD->getType()->isObjCQualifiedInterfaceType())
1780 // Simply use 'id' for all qualified types.
1781 elementTypeAsString = "id";
1782 else
1783 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1784 }
1785
1786 // struct __objcFastEnumerationState enumState = { 0 };
1787 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1788 // id __rw_items[16];
1789 buf += "id __rw_items[16];\n\t";
1790 // id l_collection = (id)
1791 buf += "id l_collection = (id)";
1792 // Find start location of 'collection' the hard way!
1793 const char *startCollectionBuf = startBuf;
1794 startCollectionBuf += 3; // skip 'for'
1795 startCollectionBuf = strchr(startCollectionBuf, '(');
1796 startCollectionBuf++; // skip '('
1797 // find 'in' and skip it.
1798 while (*startCollectionBuf != ' ' ||
1799 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1800 (*(startCollectionBuf+3) != ' ' &&
1801 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1802 startCollectionBuf++;
1803 startCollectionBuf += 3;
1804
1805 // Replace: "for (type element in" with string constructed thus far.
1806 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1807 // Replace ')' in for '(' type elem in collection ')' with ';'
1808 SourceLocation rightParenLoc = S->getRParenLoc();
1809 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1810 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1811 buf = ";\n\t";
1812
1813 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1814 // objects:__rw_items count:16];
1815 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001816 // NSUInteger limit =
1817 // ((NSUInteger (*)
1818 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001819 // (void *)objc_msgSend)((id)l_collection,
1820 // sel_registerName(
1821 // "countByEnumeratingWithState:objects:count:"),
1822 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001823 // (id *)__rw_items, (NSUInteger)16);
1824 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001825 SynthCountByEnumWithState(buf);
1826 buf += ";\n\t";
1827 /// if (limit) {
1828 /// unsigned long startMutations = *enumState.mutationsPtr;
1829 /// do {
1830 /// unsigned long counter = 0;
1831 /// do {
1832 /// if (startMutations != *enumState.mutationsPtr)
1833 /// objc_enumerationMutation(l_collection);
1834 /// elem = (type)enumState.itemsPtr[counter++];
1835 buf += "if (limit) {\n\t";
1836 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1837 buf += "do {\n\t\t";
1838 buf += "unsigned long counter = 0;\n\t\t";
1839 buf += "do {\n\t\t\t";
1840 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1841 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1842 buf += elementName;
1843 buf += " = (";
1844 buf += elementTypeAsString;
1845 buf += ")enumState.itemsPtr[counter++];";
1846 // Replace ')' in for '(' type elem in collection ')' with all of these.
1847 ReplaceText(lparenLoc, 1, buf);
1848
1849 /// __continue_label: ;
1850 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001851 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1852 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001853 /// elem = nil;
1854 /// __break_label: ;
1855 /// }
1856 /// else
1857 /// elem = nil;
1858 /// }
1859 ///
1860 buf = ";\n\t";
1861 buf += "__continue_label_";
1862 buf += utostr(ObjCBcLabelNo.back());
1863 buf += ": ;";
1864 buf += "\n\t\t";
1865 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001866 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001867 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001868 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001869 buf += elementName;
1870 buf += " = ((";
1871 buf += elementTypeAsString;
1872 buf += ")0);\n\t";
1873 buf += "__break_label_";
1874 buf += utostr(ObjCBcLabelNo.back());
1875 buf += ": ;\n\t";
1876 buf += "}\n\t";
1877 buf += "else\n\t\t";
1878 buf += elementName;
1879 buf += " = ((";
1880 buf += elementTypeAsString;
1881 buf += ")0);\n\t";
1882 buf += "}\n";
1883
1884 // Insert all these *after* the statement body.
1885 // FIXME: If this should support Obj-C++, support CXXTryStmt
1886 if (isa<CompoundStmt>(S->getBody())) {
1887 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1888 InsertText(endBodyLoc, buf);
1889 } else {
1890 /* Need to treat single statements specially. For example:
1891 *
1892 * for (A *a in b) if (stuff()) break;
1893 * for (A *a in b) xxxyy;
1894 *
1895 * The following code simply scans ahead to the semi to find the actual end.
1896 */
1897 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1898 const char *semiBuf = strchr(stmtBuf, ';');
1899 assert(semiBuf && "Can't find ';'");
1900 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1901 InsertText(endBodyLoc, buf);
1902 }
1903 Stmts.pop_back();
1904 ObjCBcLabelNo.pop_back();
1905 return 0;
1906}
1907
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001908static void Write_RethrowObject(std::string &buf) {
1909 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1910 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1911 buf += "\tid rethrow;\n";
1912 buf += "\t} _fin_force_rethow(_rethrow);";
1913}
1914
Fariborz Jahanian11671902012-02-07 17:11:38 +00001915/// RewriteObjCSynchronizedStmt -
1916/// This routine rewrites @synchronized(expr) stmt;
1917/// into:
1918/// objc_sync_enter(expr);
1919/// @try stmt @finally { objc_sync_exit(expr); }
1920///
1921Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1922 // Get the start location and compute the semi location.
1923 SourceLocation startLoc = S->getLocStart();
1924 const char *startBuf = SM->getCharacterData(startLoc);
1925
1926 assert((*startBuf == '@') && "bogus @synchronized location");
1927
1928 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001929 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1930 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001931 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001932
Fariborz Jahanian11671902012-02-07 17:11:38 +00001933 const char *lparenBuf = startBuf;
1934 while (*lparenBuf != '(') lparenBuf++;
1935 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001936
1937 buf = "; objc_sync_enter(_sync_obj);\n";
1938 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1939 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1940 buf += "\n\tid sync_exit;";
1941 buf += "\n\t} _sync_exit(_sync_obj);\n";
1942
1943 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1944 // the sync expression is typically a message expression that's already
1945 // been rewritten! (which implies the SourceLocation's are invalid).
1946 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1947 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1948 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1949 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1950
1951 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1952 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1953 assert (*LBraceLocBuf == '{');
1954 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001955
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001956 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001957 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1958 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001959
1960 buf = "} catch (id e) {_rethrow = e;}\n";
1961 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001962 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001963 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001964
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001965 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001966
Fariborz Jahanian11671902012-02-07 17:11:38 +00001967 return 0;
1968}
1969
1970void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1971{
1972 // Perform a bottom up traversal of all children.
1973 for (Stmt::child_range CI = S->children(); CI; ++CI)
1974 if (*CI)
1975 WarnAboutReturnGotoStmts(*CI);
1976
1977 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1978 Diags.Report(Context->getFullLoc(S->getLocStart()),
1979 TryFinallyContainsReturnDiag);
1980 }
1981 return;
1982}
1983
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001984Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1985 SourceLocation startLoc = S->getAtLoc();
1986 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001987 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1988 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001989
1990 return 0;
1991}
1992
Fariborz Jahanian11671902012-02-07 17:11:38 +00001993Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001994 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001995 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001996 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001997 SourceLocation TryLocation = S->getAtTryLoc();
1998 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001999
2000 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002001 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002002 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002003 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002004 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002005 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002006 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002007 // Get the start location and compute the semi location.
2008 SourceLocation startLoc = S->getLocStart();
2009 const char *startBuf = SM->getCharacterData(startLoc);
2010
2011 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002012 if (finalStmt)
2013 ReplaceText(startLoc, 1, buf);
2014 else
2015 // @try -> try
2016 ReplaceText(startLoc, 1, "");
2017
Fariborz Jahanian11671902012-02-07 17:11:38 +00002018 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2019 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002020 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002021
Fariborz Jahanian11671902012-02-07 17:11:38 +00002022 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002023 bool AtRemoved = false;
2024 if (catchDecl) {
2025 QualType t = catchDecl->getType();
2026 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2027 // Should be a pointer to a class.
2028 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2029 if (IDecl) {
2030 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002031 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2032
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002033 startBuf = SM->getCharacterData(startLoc);
2034 assert((*startBuf == '@') && "bogus @catch location");
2035 SourceLocation rParenLoc = Catch->getRParenLoc();
2036 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2037
2038 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002039 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002040 Result += " *_"; Result += catchDecl->getNameAsString();
2041 Result += ")";
2042 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2043 // Foo *e = (Foo *)_e;
2044 Result.clear();
2045 Result = "{ ";
2046 Result += IDecl->getNameAsString();
2047 Result += " *"; Result += catchDecl->getNameAsString();
2048 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2049 Result += "_"; Result += catchDecl->getNameAsString();
2050
2051 Result += "; ";
2052 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2053 ReplaceText(lBraceLoc, 1, Result);
2054 AtRemoved = true;
2055 }
2056 }
2057 }
2058 if (!AtRemoved)
2059 // @catch -> catch
2060 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002061
Fariborz Jahanian11671902012-02-07 17:11:38 +00002062 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002063 if (finalStmt) {
2064 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002065 SourceLocation FinallyLoc = finalStmt->getLocStart();
2066
2067 if (noCatch) {
2068 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2069 buf += "catch (id e) {_rethrow = e;}\n";
2070 }
2071 else {
2072 buf += "}\n";
2073 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2074 buf += "catch (id e) {_rethrow = e;}\n";
2075 }
2076
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002077 SourceLocation startFinalLoc = finalStmt->getLocStart();
2078 ReplaceText(startFinalLoc, 8, buf);
2079 Stmt *body = finalStmt->getFinallyBody();
2080 SourceLocation startFinalBodyLoc = body->getLocStart();
2081 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002082 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002083 ReplaceText(startFinalBodyLoc, 1, buf);
2084
2085 SourceLocation endFinalBodyLoc = body->getLocEnd();
2086 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002087 // Now check for any return/continue/go statements within the @try.
2088 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002089 }
2090
Fariborz Jahanian11671902012-02-07 17:11:38 +00002091 return 0;
2092}
2093
2094// This can't be done with ReplaceStmt(S, ThrowExpr), since
2095// the throw expression is typically a message expression that's already
2096// been rewritten! (which implies the SourceLocation's are invalid).
2097Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2098 // Get the start location and compute the semi location.
2099 SourceLocation startLoc = S->getLocStart();
2100 const char *startBuf = SM->getCharacterData(startLoc);
2101
2102 assert((*startBuf == '@') && "bogus @throw location");
2103
2104 std::string buf;
2105 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2106 if (S->getThrowExpr())
2107 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002108 else
2109 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002110
2111 // handle "@ throw" correctly.
2112 const char *wBuf = strchr(startBuf, 'w');
2113 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2114 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2115
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002116 SourceLocation endLoc = S->getLocEnd();
2117 const char *endBuf = SM->getCharacterData(endLoc);
2118 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002119 assert((*semiBuf == ';') && "@throw: can't find ';'");
2120 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002121 if (S->getThrowExpr())
2122 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002123 return 0;
2124}
2125
2126Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2127 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002128 std::string StrEncoding;
2129 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002130 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002131 ReplaceStmt(Exp, Replacement);
2132
2133 // Replace this subexpr in the parent.
2134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2135 return Replacement;
2136}
2137
2138Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2139 if (!SelGetUidFunctionDecl)
2140 SynthSelGetUidFunctionDecl();
2141 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2142 // Create a call to sel_registerName("selName").
2143 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002144 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002145 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2146 &SelExprs[0], SelExprs.size());
2147 ReplaceStmt(Exp, SelExp);
2148 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2149 return SelExp;
2150}
2151
2152CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2153 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2154 SourceLocation EndLoc) {
2155 // Get the type, we will need to reference it in a couple spots.
2156 QualType msgSendType = FD->getType();
2157
2158 // Create a reference to the objc_msgSend() declaration.
2159 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002160 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002161
2162 // Now, we cast the reference to a pointer to the objc_msgSend type.
2163 QualType pToFunc = Context->getPointerType(msgSendType);
2164 ImplicitCastExpr *ICE =
2165 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2166 DRE, 0, VK_RValue);
2167
2168 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2169
2170 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002171 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002172 FT->getCallResultType(*Context),
2173 VK_RValue, EndLoc);
2174 return Exp;
2175}
2176
2177static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2178 const char *&startRef, const char *&endRef) {
2179 while (startBuf < endBuf) {
2180 if (*startBuf == '<')
2181 startRef = startBuf; // mark the start.
2182 if (*startBuf == '>') {
2183 if (startRef && *startRef == '<') {
2184 endRef = startBuf; // mark the end.
2185 return true;
2186 }
2187 return false;
2188 }
2189 startBuf++;
2190 }
2191 return false;
2192}
2193
2194static void scanToNextArgument(const char *&argRef) {
2195 int angle = 0;
2196 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2197 if (*argRef == '<')
2198 angle++;
2199 else if (*argRef == '>')
2200 angle--;
2201 argRef++;
2202 }
2203 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2204}
2205
2206bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2207 if (T->isObjCQualifiedIdType())
2208 return true;
2209 if (const PointerType *PT = T->getAs<PointerType>()) {
2210 if (PT->getPointeeType()->isObjCQualifiedIdType())
2211 return true;
2212 }
2213 if (T->isObjCObjectPointerType()) {
2214 T = T->getPointeeType();
2215 return T->isObjCQualifiedInterfaceType();
2216 }
2217 if (T->isArrayType()) {
2218 QualType ElemTy = Context->getBaseElementType(T);
2219 return needToScanForQualifiers(ElemTy);
2220 }
2221 return false;
2222}
2223
2224void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2225 QualType Type = E->getType();
2226 if (needToScanForQualifiers(Type)) {
2227 SourceLocation Loc, EndLoc;
2228
2229 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2230 Loc = ECE->getLParenLoc();
2231 EndLoc = ECE->getRParenLoc();
2232 } else {
2233 Loc = E->getLocStart();
2234 EndLoc = E->getLocEnd();
2235 }
2236 // This will defend against trying to rewrite synthesized expressions.
2237 if (Loc.isInvalid() || EndLoc.isInvalid())
2238 return;
2239
2240 const char *startBuf = SM->getCharacterData(Loc);
2241 const char *endBuf = SM->getCharacterData(EndLoc);
2242 const char *startRef = 0, *endRef = 0;
2243 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2244 // Get the locations of the startRef, endRef.
2245 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2246 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2247 // Comment out the protocol references.
2248 InsertText(LessLoc, "/*");
2249 InsertText(GreaterLoc, "*/");
2250 }
2251 }
2252}
2253
2254void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2255 SourceLocation Loc;
2256 QualType Type;
2257 const FunctionProtoType *proto = 0;
2258 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2259 Loc = VD->getLocation();
2260 Type = VD->getType();
2261 }
2262 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2263 Loc = FD->getLocation();
2264 // Check for ObjC 'id' and class types that have been adorned with protocol
2265 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2266 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2267 assert(funcType && "missing function type");
2268 proto = dyn_cast<FunctionProtoType>(funcType);
2269 if (!proto)
2270 return;
Alp Toker314cc812014-01-25 16:55:45 +00002271 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002272 }
2273 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2274 Loc = FD->getLocation();
2275 Type = FD->getType();
2276 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002277 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2278 Loc = TD->getLocation();
2279 Type = TD->getUnderlyingType();
2280 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002281 else
2282 return;
2283
2284 if (needToScanForQualifiers(Type)) {
2285 // Since types are unique, we need to scan the buffer.
2286
2287 const char *endBuf = SM->getCharacterData(Loc);
2288 const char *startBuf = endBuf;
2289 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2290 startBuf--; // scan backward (from the decl location) for return type.
2291 const char *startRef = 0, *endRef = 0;
2292 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2293 // Get the locations of the startRef, endRef.
2294 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2295 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2296 // Comment out the protocol references.
2297 InsertText(LessLoc, "/*");
2298 InsertText(GreaterLoc, "*/");
2299 }
2300 }
2301 if (!proto)
2302 return; // most likely, was a variable
2303 // Now check arguments.
2304 const char *startBuf = SM->getCharacterData(Loc);
2305 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002306 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2307 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002308 // Since types are unique, we need to scan the buffer.
2309
2310 const char *endBuf = startBuf;
2311 // scan forward (from the decl location) for argument types.
2312 scanToNextArgument(endBuf);
2313 const char *startRef = 0, *endRef = 0;
2314 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2315 // Get the locations of the startRef, endRef.
2316 SourceLocation LessLoc =
2317 Loc.getLocWithOffset(startRef-startFuncBuf);
2318 SourceLocation GreaterLoc =
2319 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2320 // Comment out the protocol references.
2321 InsertText(LessLoc, "/*");
2322 InsertText(GreaterLoc, "*/");
2323 }
2324 startBuf = ++endBuf;
2325 }
2326 else {
2327 // If the function name is derived from a macro expansion, then the
2328 // argument buffer will not follow the name. Need to speak with Chris.
2329 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2330 startBuf++; // scan forward (from the decl location) for argument types.
2331 startBuf++;
2332 }
2333 }
2334}
2335
2336void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2337 QualType QT = ND->getType();
2338 const Type* TypePtr = QT->getAs<Type>();
2339 if (!isa<TypeOfExprType>(TypePtr))
2340 return;
2341 while (isa<TypeOfExprType>(TypePtr)) {
2342 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2343 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2344 TypePtr = QT->getAs<Type>();
2345 }
2346 // FIXME. This will not work for multiple declarators; as in:
2347 // __typeof__(a) b,c,d;
2348 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2349 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2350 const char *startBuf = SM->getCharacterData(DeclLoc);
2351 if (ND->getInit()) {
2352 std::string Name(ND->getNameAsString());
2353 TypeAsString += " " + Name + " = ";
2354 Expr *E = ND->getInit();
2355 SourceLocation startLoc;
2356 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2357 startLoc = ECE->getLParenLoc();
2358 else
2359 startLoc = E->getLocStart();
2360 startLoc = SM->getExpansionLoc(startLoc);
2361 const char *endBuf = SM->getCharacterData(startLoc);
2362 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2363 }
2364 else {
2365 SourceLocation X = ND->getLocEnd();
2366 X = SM->getExpansionLoc(X);
2367 const char *endBuf = SM->getCharacterData(X);
2368 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2369 }
2370}
2371
2372// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2373void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2374 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2375 SmallVector<QualType, 16> ArgTys;
2376 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2377 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002378 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002379 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002380 SourceLocation(),
2381 SourceLocation(),
2382 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002383 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002384}
2385
2386void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2387 // declared in <objc/objc.h>
2388 if (FD->getIdentifier() &&
2389 FD->getName() == "sel_registerName") {
2390 SelGetUidFunctionDecl = FD;
2391 return;
2392 }
2393 RewriteObjCQualifiedInterfaceTypes(FD);
2394}
2395
2396void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2397 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2398 const char *argPtr = TypeString.c_str();
2399 if (!strchr(argPtr, '^')) {
2400 Str += TypeString;
2401 return;
2402 }
2403 while (*argPtr) {
2404 Str += (*argPtr == '^' ? '*' : *argPtr);
2405 argPtr++;
2406 }
2407}
2408
2409// FIXME. Consolidate this routine with RewriteBlockPointerType.
2410void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2411 ValueDecl *VD) {
2412 QualType Type = VD->getType();
2413 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2414 const char *argPtr = TypeString.c_str();
2415 int paren = 0;
2416 while (*argPtr) {
2417 switch (*argPtr) {
2418 case '(':
2419 Str += *argPtr;
2420 paren++;
2421 break;
2422 case ')':
2423 Str += *argPtr;
2424 paren--;
2425 break;
2426 case '^':
2427 Str += '*';
2428 if (paren == 1)
2429 Str += VD->getNameAsString();
2430 break;
2431 default:
2432 Str += *argPtr;
2433 break;
2434 }
2435 argPtr++;
2436 }
2437}
2438
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002439void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2440 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2441 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2442 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2443 if (!proto)
2444 return;
Alp Toker314cc812014-01-25 16:55:45 +00002445 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002446 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2447 FdStr += " ";
2448 FdStr += FD->getName();
2449 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002450 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002451 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002452 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002453 RewriteBlockPointerType(FdStr, ArgType);
2454 if (i+1 < numArgs)
2455 FdStr += ", ";
2456 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002457 if (FD->isVariadic()) {
2458 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2459 }
2460 else
2461 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002462 InsertText(FunLocStart, FdStr);
2463}
2464
Benjamin Kramer60509af2013-09-09 14:48:42 +00002465// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2466void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2467 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002468 return;
2469 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2470 SmallVector<QualType, 16> ArgTys;
2471 QualType argT = Context->getObjCIdType();
2472 assert(!argT.isNull() && "Can't find 'id' type");
2473 ArgTys.push_back(argT);
2474 ArgTys.push_back(argT);
2475 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002476 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002477 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002478 SourceLocation(),
2479 SourceLocation(),
2480 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002481 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002482}
2483
2484// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2485void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2486 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2487 SmallVector<QualType, 16> ArgTys;
2488 QualType argT = Context->getObjCIdType();
2489 assert(!argT.isNull() && "Can't find 'id' type");
2490 ArgTys.push_back(argT);
2491 argT = Context->getObjCSelType();
2492 assert(!argT.isNull() && "Can't find 'SEL' type");
2493 ArgTys.push_back(argT);
2494 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002495 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002496 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002497 SourceLocation(),
2498 SourceLocation(),
2499 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002500 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002501}
2502
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002503// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002504void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2505 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002506 SmallVector<QualType, 2> ArgTys;
2507 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002508 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002509 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002510 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002511 SourceLocation(),
2512 SourceLocation(),
2513 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002514 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002515}
2516
2517// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2518void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2519 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2520 SmallVector<QualType, 16> ArgTys;
2521 QualType argT = Context->getObjCIdType();
2522 assert(!argT.isNull() && "Can't find 'id' type");
2523 ArgTys.push_back(argT);
2524 argT = Context->getObjCSelType();
2525 assert(!argT.isNull() && "Can't find 'SEL' type");
2526 ArgTys.push_back(argT);
2527 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002528 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002529 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002530 SourceLocation(),
2531 SourceLocation(),
2532 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002533 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002534}
2535
2536// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002537// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002538void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2539 IdentifierInfo *msgSendIdent =
2540 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002541 SmallVector<QualType, 2> ArgTys;
2542 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002543 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002544 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002545 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2546 SourceLocation(),
2547 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002548 msgSendIdent,
2549 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002550 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002551}
2552
2553// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2554void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2555 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2556 SmallVector<QualType, 16> ArgTys;
2557 QualType argT = Context->getObjCIdType();
2558 assert(!argT.isNull() && "Can't find 'id' type");
2559 ArgTys.push_back(argT);
2560 argT = Context->getObjCSelType();
2561 assert(!argT.isNull() && "Can't find 'SEL' type");
2562 ArgTys.push_back(argT);
2563 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002564 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002565 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002566 SourceLocation(),
2567 SourceLocation(),
2568 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002569 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002570}
2571
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002572// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002573void RewriteModernObjC::SynthGetClassFunctionDecl() {
2574 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2575 SmallVector<QualType, 16> ArgTys;
2576 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002577 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002578 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002579 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002580 SourceLocation(),
2581 SourceLocation(),
2582 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002583 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002584}
2585
2586// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2587void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2588 IdentifierInfo *getSuperClassIdent =
2589 &Context->Idents.get("class_getSuperclass");
2590 SmallVector<QualType, 16> ArgTys;
2591 ArgTys.push_back(Context->getObjCClassType());
2592 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002593 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002594 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2595 SourceLocation(),
2596 SourceLocation(),
2597 getSuperClassIdent,
2598 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002599 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002600}
2601
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002602// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002603void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2604 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2605 SmallVector<QualType, 16> ArgTys;
2606 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002607 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002608 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002609 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002610 SourceLocation(),
2611 SourceLocation(),
2612 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002613 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002614}
2615
2616Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2617 QualType strType = getConstantStringStructType();
2618
2619 std::string S = "__NSConstantStringImpl_";
2620
2621 std::string tmpName = InFileName;
2622 unsigned i;
2623 for (i=0; i < tmpName.length(); i++) {
2624 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002625 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002626 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002627 tmpName[i] = '_';
2628 }
2629 S += tmpName;
2630 S += "_";
2631 S += utostr(NumObjCStringLiterals++);
2632
2633 Preamble += "static __NSConstantStringImpl " + S;
2634 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2635 Preamble += "0x000007c8,"; // utf8_str
2636 // The pretty printer for StringLiteral handles escape characters properly.
2637 std::string prettyBufS;
2638 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002639 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002640 Preamble += prettyBuf.str();
2641 Preamble += ",";
2642 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2643
2644 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2645 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002646 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002647 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002648 SourceLocation());
2649 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2650 Context->getPointerType(DRE->getType()),
2651 VK_RValue, OK_Ordinary,
2652 SourceLocation());
2653 // cast to NSConstantString *
2654 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2655 CK_CPointerToObjCPointerCast, Unop);
2656 ReplaceStmt(Exp, cast);
2657 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2658 return cast;
2659}
2660
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002661Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2662 unsigned IntSize =
2663 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2664
2665 Expr *FlagExp = IntegerLiteral::Create(*Context,
2666 llvm::APInt(IntSize, Exp->getValue()),
2667 Context->IntTy, Exp->getLocation());
2668 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2669 CK_BitCast, FlagExp);
2670 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2671 cast);
2672 ReplaceStmt(Exp, PE);
2673 return PE;
2674}
2675
Patrick Beard0caa3942012-04-19 00:25:12 +00002676Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002677 // synthesize declaration of helper functions needed in this routine.
2678 if (!SelGetUidFunctionDecl)
2679 SynthSelGetUidFunctionDecl();
2680 // use objc_msgSend() for all.
2681 if (!MsgSendFunctionDecl)
2682 SynthMsgSendFunctionDecl();
2683 if (!GetClassFunctionDecl)
2684 SynthGetClassFunctionDecl();
2685
2686 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2687 SourceLocation StartLoc = Exp->getLocStart();
2688 SourceLocation EndLoc = Exp->getLocEnd();
2689
2690 // Synthesize a call to objc_msgSend().
2691 SmallVector<Expr*, 4> MsgExprs;
2692 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002693
Patrick Beard0caa3942012-04-19 00:25:12 +00002694 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2695 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2696 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002697
Patrick Beard0caa3942012-04-19 00:25:12 +00002698 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002699 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002700 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2701 &ClsExprs[0],
2702 ClsExprs.size(),
2703 StartLoc, EndLoc);
2704 MsgExprs.push_back(Cls);
2705
Patrick Beard0caa3942012-04-19 00:25:12 +00002706 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002707 // it will be the 2nd argument.
2708 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002709 SelExprs.push_back(
2710 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002711 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2712 &SelExprs[0], SelExprs.size(),
2713 StartLoc, EndLoc);
2714 MsgExprs.push_back(SelExp);
2715
Patrick Beard0caa3942012-04-19 00:25:12 +00002716 // User provided sub-expression is the 3rd, and last, argument.
2717 Expr *subExpr = Exp->getSubExpr();
2718 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002719 QualType type = ICE->getType();
2720 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2721 CastKind CK = CK_BitCast;
2722 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2723 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002724 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002725 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002726 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002727
2728 SmallVector<QualType, 4> ArgTypes;
2729 ArgTypes.push_back(Context->getObjCIdType());
2730 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002731 for (const auto PI : BoxingMethod->parameters())
2732 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002733
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002734 QualType returnType = Exp->getType();
2735 // Get the type, we will need to reference it in a couple spots.
2736 QualType msgSendType = MsgSendFlavor->getType();
2737
2738 // Create a reference to the objc_msgSend() declaration.
2739 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2740 VK_LValue, SourceLocation());
2741
2742 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002743 Context->getPointerType(Context->VoidTy),
2744 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002745
2746 // Now do the "normal" pointer to function cast.
2747 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002748 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002749 castType = Context->getPointerType(castType);
2750 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2751 cast);
2752
2753 // Don't forget the parens to enforce the proper binding.
2754 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2755
2756 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002757 CallExpr *CE = new (Context)
2758 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002759 ReplaceStmt(Exp, CE);
2760 return CE;
2761}
2762
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002763Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2764 // synthesize declaration of helper functions needed in this routine.
2765 if (!SelGetUidFunctionDecl)
2766 SynthSelGetUidFunctionDecl();
2767 // use objc_msgSend() for all.
2768 if (!MsgSendFunctionDecl)
2769 SynthMsgSendFunctionDecl();
2770 if (!GetClassFunctionDecl)
2771 SynthGetClassFunctionDecl();
2772
2773 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2774 SourceLocation StartLoc = Exp->getLocStart();
2775 SourceLocation EndLoc = Exp->getLocEnd();
2776
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002777 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002778 QualType IntQT = Context->IntTy;
2779 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002780 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002781 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002782 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2783 DeclRefExpr *NSArrayDRE =
2784 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2785 SourceLocation());
2786
2787 SmallVector<Expr*, 16> InitExprs;
2788 unsigned NumElements = Exp->getNumElements();
2789 unsigned UnsignedIntSize =
2790 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2791 Expr *count = IntegerLiteral::Create(*Context,
2792 llvm::APInt(UnsignedIntSize, NumElements),
2793 Context->UnsignedIntTy, SourceLocation());
2794 InitExprs.push_back(count);
2795 for (unsigned i = 0; i < NumElements; i++)
2796 InitExprs.push_back(Exp->getElement(i));
2797 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002798 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002799 NSArrayFType, VK_LValue, SourceLocation());
2800
2801 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2802 SourceLocation(),
2803 &Context->Idents.get("arr"),
2804 Context->getPointerType(Context->VoidPtrTy), 0,
2805 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002806 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002807 MemberExpr *ArrayLiteralME =
2808 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2809 SourceLocation(),
2810 ARRFD->getType(), VK_LValue,
2811 OK_Ordinary);
2812 QualType ConstIdT = Context->getObjCIdType().withConst();
2813 CStyleCastExpr * ArrayLiteralObjects =
2814 NoTypeInfoCStyleCastExpr(Context,
2815 Context->getPointerType(ConstIdT),
2816 CK_BitCast,
2817 ArrayLiteralME);
2818
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002819 // Synthesize a call to objc_msgSend().
2820 SmallVector<Expr*, 32> MsgExprs;
2821 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002822 QualType expType = Exp->getType();
2823
2824 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2825 ObjCInterfaceDecl *Class =
2826 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2827
2828 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002829 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002830 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2831 &ClsExprs[0],
2832 ClsExprs.size(),
2833 StartLoc, EndLoc);
2834 MsgExprs.push_back(Cls);
2835
2836 // Create a call to sel_registerName("arrayWithObjects:count:").
2837 // it will be the 2nd argument.
2838 SmallVector<Expr*, 4> SelExprs;
2839 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002840 SelExprs.push_back(
2841 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002842 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2843 &SelExprs[0], SelExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002847 // (const id [])objects
2848 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002849
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002850 // (NSUInteger)cnt
2851 Expr *cnt = IntegerLiteral::Create(*Context,
2852 llvm::APInt(UnsignedIntSize, NumElements),
2853 Context->UnsignedIntTy, SourceLocation());
2854 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002855
2856
2857 SmallVector<QualType, 4> ArgTypes;
2858 ArgTypes.push_back(Context->getObjCIdType());
2859 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002860 for (const auto *PI : ArrayMethod->params())
2861 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002862
2863 QualType returnType = Exp->getType();
2864 // Get the type, we will need to reference it in a couple spots.
2865 QualType msgSendType = MsgSendFlavor->getType();
2866
2867 // Create a reference to the objc_msgSend() declaration.
2868 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2869 VK_LValue, SourceLocation());
2870
2871 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2872 Context->getPointerType(Context->VoidTy),
2873 CK_BitCast, DRE);
2874
2875 // Now do the "normal" pointer to function cast.
2876 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002877 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002878 castType = Context->getPointerType(castType);
2879 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2880 cast);
2881
2882 // Don't forget the parens to enforce the proper binding.
2883 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2884
2885 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002886 CallExpr *CE = new (Context)
2887 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002888 ReplaceStmt(Exp, CE);
2889 return CE;
2890}
2891
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002892Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2893 // synthesize declaration of helper functions needed in this routine.
2894 if (!SelGetUidFunctionDecl)
2895 SynthSelGetUidFunctionDecl();
2896 // use objc_msgSend() for all.
2897 if (!MsgSendFunctionDecl)
2898 SynthMsgSendFunctionDecl();
2899 if (!GetClassFunctionDecl)
2900 SynthGetClassFunctionDecl();
2901
2902 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2903 SourceLocation StartLoc = Exp->getLocStart();
2904 SourceLocation EndLoc = Exp->getLocEnd();
2905
2906 // Build the expression: __NSContainer_literal(int, ...).arr
2907 QualType IntQT = Context->IntTy;
2908 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002909 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002910 std::string NSDictFName("__NSContainer_literal");
2911 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2912 DeclRefExpr *NSDictDRE =
2913 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2914 SourceLocation());
2915
2916 SmallVector<Expr*, 16> KeyExprs;
2917 SmallVector<Expr*, 16> ValueExprs;
2918
2919 unsigned NumElements = Exp->getNumElements();
2920 unsigned UnsignedIntSize =
2921 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2922 Expr *count = IntegerLiteral::Create(*Context,
2923 llvm::APInt(UnsignedIntSize, NumElements),
2924 Context->UnsignedIntTy, SourceLocation());
2925 KeyExprs.push_back(count);
2926 ValueExprs.push_back(count);
2927 for (unsigned i = 0; i < NumElements; i++) {
2928 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2929 KeyExprs.push_back(Element.Key);
2930 ValueExprs.push_back(Element.Value);
2931 }
2932
2933 // (const id [])objects
2934 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002935 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002936 NSDictFType, VK_LValue, SourceLocation());
2937
2938 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2939 SourceLocation(),
2940 &Context->Idents.get("arr"),
2941 Context->getPointerType(Context->VoidPtrTy), 0,
2942 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002943 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002944 MemberExpr *DictLiteralValueME =
2945 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2946 SourceLocation(),
2947 ARRFD->getType(), VK_LValue,
2948 OK_Ordinary);
2949 QualType ConstIdT = Context->getObjCIdType().withConst();
2950 CStyleCastExpr * DictValueObjects =
2951 NoTypeInfoCStyleCastExpr(Context,
2952 Context->getPointerType(ConstIdT),
2953 CK_BitCast,
2954 DictLiteralValueME);
2955 // (const id <NSCopying> [])keys
2956 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002957 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002958 NSDictFType, VK_LValue, SourceLocation());
2959
2960 MemberExpr *DictLiteralKeyME =
2961 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2962 SourceLocation(),
2963 ARRFD->getType(), VK_LValue,
2964 OK_Ordinary);
2965
2966 CStyleCastExpr * DictKeyObjects =
2967 NoTypeInfoCStyleCastExpr(Context,
2968 Context->getPointerType(ConstIdT),
2969 CK_BitCast,
2970 DictLiteralKeyME);
2971
2972
2973
2974 // Synthesize a call to objc_msgSend().
2975 SmallVector<Expr*, 32> MsgExprs;
2976 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002977 QualType expType = Exp->getType();
2978
2979 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2980 ObjCInterfaceDecl *Class =
2981 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2982
2983 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002984 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002985 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2986 &ClsExprs[0],
2987 ClsExprs.size(),
2988 StartLoc, EndLoc);
2989 MsgExprs.push_back(Cls);
2990
2991 // Create a call to sel_registerName("arrayWithObjects:count:").
2992 // it will be the 2nd argument.
2993 SmallVector<Expr*, 4> SelExprs;
2994 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002995 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002996 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2997 &SelExprs[0], SelExprs.size(),
2998 StartLoc, EndLoc);
2999 MsgExprs.push_back(SelExp);
3000
3001 // (const id [])objects
3002 MsgExprs.push_back(DictValueObjects);
3003
3004 // (const id <NSCopying> [])keys
3005 MsgExprs.push_back(DictKeyObjects);
3006
3007 // (NSUInteger)cnt
3008 Expr *cnt = IntegerLiteral::Create(*Context,
3009 llvm::APInt(UnsignedIntSize, NumElements),
3010 Context->UnsignedIntTy, SourceLocation());
3011 MsgExprs.push_back(cnt);
3012
3013
3014 SmallVector<QualType, 8> ArgTypes;
3015 ArgTypes.push_back(Context->getObjCIdType());
3016 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00003017 for (const auto *PI : DictMethod->params()) {
3018 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003019 if (const PointerType* PT = T->getAs<PointerType>()) {
3020 QualType PointeeTy = PT->getPointeeType();
3021 convertToUnqualifiedObjCType(PointeeTy);
3022 T = Context->getPointerType(PointeeTy);
3023 }
3024 ArgTypes.push_back(T);
3025 }
3026
3027 QualType returnType = Exp->getType();
3028 // Get the type, we will need to reference it in a couple spots.
3029 QualType msgSendType = MsgSendFlavor->getType();
3030
3031 // Create a reference to the objc_msgSend() declaration.
3032 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3033 VK_LValue, SourceLocation());
3034
3035 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3036 Context->getPointerType(Context->VoidTy),
3037 CK_BitCast, DRE);
3038
3039 // Now do the "normal" pointer to function cast.
3040 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003041 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003042 castType = Context->getPointerType(castType);
3043 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3044 cast);
3045
3046 // Don't forget the parens to enforce the proper binding.
3047 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3048
3049 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003050 CallExpr *CE = new (Context)
3051 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003052 ReplaceStmt(Exp, CE);
3053 return CE;
3054}
3055
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003056// struct __rw_objc_super {
3057// struct objc_object *object; struct objc_object *superClass;
3058// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003059QualType RewriteModernObjC::getSuperStructType() {
3060 if (!SuperStructDecl) {
3061 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3062 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003063 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003064 QualType FieldTypes[2];
3065
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003066 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003067 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003068 // struct objc_object *superClass;
3069 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003070
3071 // Create fields
3072 for (unsigned i = 0; i < 2; ++i) {
3073 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3074 SourceLocation(),
3075 SourceLocation(), 0,
3076 FieldTypes[i], 0,
3077 /*BitWidth=*/0,
3078 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003079 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003080 }
3081
3082 SuperStructDecl->completeDefinition();
3083 }
3084 return Context->getTagDeclType(SuperStructDecl);
3085}
3086
3087QualType RewriteModernObjC::getConstantStringStructType() {
3088 if (!ConstantStringDecl) {
3089 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3090 SourceLocation(), SourceLocation(),
3091 &Context->Idents.get("__NSConstantStringImpl"));
3092 QualType FieldTypes[4];
3093
3094 // struct objc_object *receiver;
3095 FieldTypes[0] = Context->getObjCIdType();
3096 // int flags;
3097 FieldTypes[1] = Context->IntTy;
3098 // char *str;
3099 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3100 // long length;
3101 FieldTypes[3] = Context->LongTy;
3102
3103 // Create fields
3104 for (unsigned i = 0; i < 4; ++i) {
3105 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3106 ConstantStringDecl,
3107 SourceLocation(),
3108 SourceLocation(), 0,
3109 FieldTypes[i], 0,
3110 /*BitWidth=*/0,
3111 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003112 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003113 }
3114
3115 ConstantStringDecl->completeDefinition();
3116 }
3117 return Context->getTagDeclType(ConstantStringDecl);
3118}
3119
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003120/// getFunctionSourceLocation - returns start location of a function
3121/// definition. Complication arises when function has declared as
3122/// extern "C" or extern "C" {...}
3123static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3124 FunctionDecl *FD) {
3125 if (FD->isExternC() && !FD->isMain()) {
3126 const DeclContext *DC = FD->getDeclContext();
3127 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3128 // if it is extern "C" {...}, return function decl's own location.
3129 if (!LSD->getRBraceLoc().isValid())
3130 return LSD->getExternLoc();
3131 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003132 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003133 R.RewriteBlockLiteralFunctionDecl(FD);
3134 return FD->getTypeSpecStartLoc();
3135}
3136
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003137void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3138
3139 SourceLocation Location = D->getLocation();
3140
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003141 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003142 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003143 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3144 LineString += utostr(PLoc.getLine());
3145 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003146 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003147 if (isa<ObjCMethodDecl>(D))
3148 LineString += "\"";
3149 else LineString += "\"\n";
3150
3151 Location = D->getLocStart();
3152 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3153 if (FD->isExternC() && !FD->isMain()) {
3154 const DeclContext *DC = FD->getDeclContext();
3155 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3156 // if it is extern "C" {...}, return function decl's own location.
3157 if (!LSD->getRBraceLoc().isValid())
3158 Location = LSD->getExternLoc();
3159 }
3160 }
3161 InsertText(Location, LineString);
3162 }
3163}
3164
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003165/// SynthMsgSendStretCallExpr - This routine translates message expression
3166/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3167/// nil check on receiver must be performed before calling objc_msgSend_stret.
3168/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3169/// msgSendType - function type of objc_msgSend_stret(...)
3170/// returnType - Result type of the method being synthesized.
3171/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3172/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3173/// starting with receiver.
3174/// Method - Method being rewritten.
3175Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003176 QualType returnType,
3177 SmallVectorImpl<QualType> &ArgTypes,
3178 SmallVectorImpl<Expr*> &MsgExprs,
3179 ObjCMethodDecl *Method) {
3180 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003181 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3182 Method ? Method->isVariadic()
3183 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003184 castType = Context->getPointerType(castType);
3185
3186 // build type for containing the objc_msgSend_stret object.
3187 static unsigned stretCount=0;
3188 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003189 std::string str =
3190 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003191 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003192 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003193 str += " {\n\t";
3194 str += name;
3195 str += "(id receiver, SEL sel";
3196 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003197 std::string ArgName = "arg"; ArgName += utostr(i);
3198 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3199 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003200 }
3201 // could be vararg.
3202 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003203 std::string ArgName = "arg"; ArgName += utostr(i);
3204 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3205 Context->getPrintingPolicy());
3206 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003207 }
3208
3209 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003210 str += "\t unsigned size = sizeof(";
3211 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3212
3213 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3214
3215 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3216 str += ")(void *)objc_msgSend)(receiver, sel";
3217 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3218 str += ", arg"; str += utostr(i);
3219 }
3220 // could be vararg.
3221 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3222 str += ", arg"; str += utostr(i);
3223 }
3224 str+= ");\n";
3225
3226 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003227 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3228 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003229
3230
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003231 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3232 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3233 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3234 str += ", arg"; str += utostr(i);
3235 }
3236 // could be vararg.
3237 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3238 str += ", arg"; str += utostr(i);
3239 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003240 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003241
3242
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003243 str += "\t}\n";
3244 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3245 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003246 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003247 SourceLocation FunLocStart;
3248 if (CurFunctionDef)
3249 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3250 else {
3251 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3252 FunLocStart = CurMethodDef->getLocStart();
3253 }
3254
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003255 InsertText(FunLocStart, str);
3256 ++stretCount;
3257
3258 // AST for __Stretn(receiver, args).s;
3259 IdentifierInfo *ID = &Context->Idents.get(name);
3260 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003261 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003262 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003263 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3264 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003265 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003266 castType, VK_LValue, SourceLocation());
3267
3268 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3269 SourceLocation(),
3270 &Context->Idents.get("s"),
3271 returnType, 0,
3272 /*BitWidth=*/0, /*Mutable=*/true,
3273 ICIS_NoInit);
3274 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3275 FieldD->getType(), VK_LValue,
3276 OK_Ordinary);
3277
3278 return ME;
3279}
3280
Fariborz Jahanian11671902012-02-07 17:11:38 +00003281Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3282 SourceLocation StartLoc,
3283 SourceLocation EndLoc) {
3284 if (!SelGetUidFunctionDecl)
3285 SynthSelGetUidFunctionDecl();
3286 if (!MsgSendFunctionDecl)
3287 SynthMsgSendFunctionDecl();
3288 if (!MsgSendSuperFunctionDecl)
3289 SynthMsgSendSuperFunctionDecl();
3290 if (!MsgSendStretFunctionDecl)
3291 SynthMsgSendStretFunctionDecl();
3292 if (!MsgSendSuperStretFunctionDecl)
3293 SynthMsgSendSuperStretFunctionDecl();
3294 if (!MsgSendFpretFunctionDecl)
3295 SynthMsgSendFpretFunctionDecl();
3296 if (!GetClassFunctionDecl)
3297 SynthGetClassFunctionDecl();
3298 if (!GetSuperClassFunctionDecl)
3299 SynthGetSuperClassFunctionDecl();
3300 if (!GetMetaClassFunctionDecl)
3301 SynthGetMetaClassFunctionDecl();
3302
3303 // default to objc_msgSend().
3304 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3305 // May need to use objc_msgSend_stret() as well.
3306 FunctionDecl *MsgSendStretFlavor = 0;
3307 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003308 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003309 if (resultType->isRecordType())
3310 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3311 else if (resultType->isRealFloatingType())
3312 MsgSendFlavor = MsgSendFpretFunctionDecl;
3313 }
3314
3315 // Synthesize a call to objc_msgSend().
3316 SmallVector<Expr*, 8> MsgExprs;
3317 switch (Exp->getReceiverKind()) {
3318 case ObjCMessageExpr::SuperClass: {
3319 MsgSendFlavor = MsgSendSuperFunctionDecl;
3320 if (MsgSendStretFlavor)
3321 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3322 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3323
3324 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3325
3326 SmallVector<Expr*, 4> InitExprs;
3327
3328 // set the receiver to self, the first argument to all methods.
3329 InitExprs.push_back(
3330 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3331 CK_BitCast,
3332 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003333 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003334 Context->getObjCIdType(),
3335 VK_RValue,
3336 SourceLocation()))
3337 ); // set the 'receiver'.
3338
3339 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3340 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003341 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003342 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003343 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3344 &ClsExprs[0],
3345 ClsExprs.size(),
3346 StartLoc,
3347 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003348 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003349 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003350 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3351 &ClsExprs[0], ClsExprs.size(),
3352 StartLoc, EndLoc);
3353
3354 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3355 // To turn off a warning, type-cast to 'id'
3356 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3357 NoTypeInfoCStyleCastExpr(Context,
3358 Context->getObjCIdType(),
3359 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003360 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003361 QualType superType = getSuperStructType();
3362 Expr *SuperRep;
3363
3364 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003365 SynthSuperConstructorFunctionDecl();
3366 // Simulate a constructor call...
3367 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003368 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003369 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003370 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003371 superType, VK_LValue,
3372 SourceLocation());
3373 // The code for super is a little tricky to prevent collision with
3374 // the structure definition in the header. The rewriter has it's own
3375 // internal definition (__rw_objc_super) that is uses. This is why
3376 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003377 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003378 //
3379 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3380 Context->getPointerType(SuperRep->getType()),
3381 VK_RValue, OK_Ordinary,
3382 SourceLocation());
3383 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3384 Context->getPointerType(superType),
3385 CK_BitCast, SuperRep);
3386 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003387 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003388 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003389 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003390 SourceLocation());
3391 TypeSourceInfo *superTInfo
3392 = Context->getTrivialTypeSourceInfo(superType);
3393 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3394 superType, VK_LValue,
3395 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003396 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003397 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3398 Context->getPointerType(SuperRep->getType()),
3399 VK_RValue, OK_Ordinary,
3400 SourceLocation());
3401 }
3402 MsgExprs.push_back(SuperRep);
3403 break;
3404 }
3405
3406 case ObjCMessageExpr::Class: {
3407 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003408 ObjCInterfaceDecl *Class
3409 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3410 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003411 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003412 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3413 &ClsExprs[0],
3414 ClsExprs.size(),
3415 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003416 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3417 Context->getObjCIdType(),
3418 CK_BitCast, Cls);
3419 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003420 break;
3421 }
3422
3423 case ObjCMessageExpr::SuperInstance:{
3424 MsgSendFlavor = MsgSendSuperFunctionDecl;
3425 if (MsgSendStretFlavor)
3426 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3427 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3428 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3429 SmallVector<Expr*, 4> InitExprs;
3430
3431 InitExprs.push_back(
3432 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3433 CK_BitCast,
3434 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003435 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003436 Context->getObjCIdType(),
3437 VK_RValue, SourceLocation()))
3438 ); // set the 'receiver'.
3439
3440 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3441 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003442 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003443 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003444 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3445 &ClsExprs[0],
3446 ClsExprs.size(),
3447 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003448 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003449 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003450 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3451 &ClsExprs[0], ClsExprs.size(),
3452 StartLoc, EndLoc);
3453
3454 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3455 // To turn off a warning, type-cast to 'id'
3456 InitExprs.push_back(
3457 // set 'super class', using class_getSuperclass().
3458 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3459 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003460 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003461 QualType superType = getSuperStructType();
3462 Expr *SuperRep;
3463
3464 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003465 SynthSuperConstructorFunctionDecl();
3466 // Simulate a constructor call...
3467 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003468 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003469 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003470 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003471 superType, VK_LValue, SourceLocation());
3472 // The code for super is a little tricky to prevent collision with
3473 // the structure definition in the header. The rewriter has it's own
3474 // internal definition (__rw_objc_super) that is uses. This is why
3475 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003476 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003477 //
3478 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3479 Context->getPointerType(SuperRep->getType()),
3480 VK_RValue, OK_Ordinary,
3481 SourceLocation());
3482 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3483 Context->getPointerType(superType),
3484 CK_BitCast, SuperRep);
3485 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003486 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003487 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003488 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003489 SourceLocation());
3490 TypeSourceInfo *superTInfo
3491 = Context->getTrivialTypeSourceInfo(superType);
3492 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3493 superType, VK_RValue, ILE,
3494 false);
3495 }
3496 MsgExprs.push_back(SuperRep);
3497 break;
3498 }
3499
3500 case ObjCMessageExpr::Instance: {
3501 // Remove all type-casts because it may contain objc-style types; e.g.
3502 // Foo<Proto> *.
3503 Expr *recExpr = Exp->getInstanceReceiver();
3504 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3505 recExpr = CE->getSubExpr();
3506 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3507 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3508 ? CK_BlockPointerToObjCPointerCast
3509 : CK_CPointerToObjCPointerCast;
3510
3511 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3512 CK, recExpr);
3513 MsgExprs.push_back(recExpr);
3514 break;
3515 }
3516 }
3517
3518 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3519 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003520 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003521 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3522 &SelExprs[0], SelExprs.size(),
3523 StartLoc,
3524 EndLoc);
3525 MsgExprs.push_back(SelExp);
3526
3527 // Now push any user supplied arguments.
3528 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3529 Expr *userExpr = Exp->getArg(i);
3530 // Make all implicit casts explicit...ICE comes in handy:-)
3531 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3532 // Reuse the ICE type, it is exactly what the doctor ordered.
3533 QualType type = ICE->getType();
3534 if (needToScanForQualifiers(type))
3535 type = Context->getObjCIdType();
3536 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3537 (void)convertBlockPointerToFunctionPointer(type);
3538 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3539 CastKind CK;
3540 if (SubExpr->getType()->isIntegralType(*Context) &&
3541 type->isBooleanType()) {
3542 CK = CK_IntegralToBoolean;
3543 } else if (type->isObjCObjectPointerType()) {
3544 if (SubExpr->getType()->isBlockPointerType()) {
3545 CK = CK_BlockPointerToObjCPointerCast;
3546 } else if (SubExpr->getType()->isPointerType()) {
3547 CK = CK_CPointerToObjCPointerCast;
3548 } else {
3549 CK = CK_BitCast;
3550 }
3551 } else {
3552 CK = CK_BitCast;
3553 }
3554
3555 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3556 }
3557 // Make id<P...> cast into an 'id' cast.
3558 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3559 if (CE->getType()->isObjCQualifiedIdType()) {
3560 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3561 userExpr = CE->getSubExpr();
3562 CastKind CK;
3563 if (userExpr->getType()->isIntegralType(*Context)) {
3564 CK = CK_IntegralToPointer;
3565 } else if (userExpr->getType()->isBlockPointerType()) {
3566 CK = CK_BlockPointerToObjCPointerCast;
3567 } else if (userExpr->getType()->isPointerType()) {
3568 CK = CK_CPointerToObjCPointerCast;
3569 } else {
3570 CK = CK_BitCast;
3571 }
3572 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3573 CK, userExpr);
3574 }
3575 }
3576 MsgExprs.push_back(userExpr);
3577 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3578 // out the argument in the original expression (since we aren't deleting
3579 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3580 //Exp->setArg(i, 0);
3581 }
3582 // Generate the funky cast.
3583 CastExpr *cast;
3584 SmallVector<QualType, 8> ArgTypes;
3585 QualType returnType;
3586
3587 // Push 'id' and 'SEL', the 2 implicit arguments.
3588 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3589 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3590 else
3591 ArgTypes.push_back(Context->getObjCIdType());
3592 ArgTypes.push_back(Context->getObjCSelType());
3593 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3594 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003595 for (const auto *PI : OMD->params()) {
3596 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003597 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003598 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003599 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3600 (void)convertBlockPointerToFunctionPointer(t);
3601 ArgTypes.push_back(t);
3602 }
3603 returnType = Exp->getType();
3604 convertToUnqualifiedObjCType(returnType);
3605 (void)convertBlockPointerToFunctionPointer(returnType);
3606 } else {
3607 returnType = Context->getObjCIdType();
3608 }
3609 // Get the type, we will need to reference it in a couple spots.
3610 QualType msgSendType = MsgSendFlavor->getType();
3611
3612 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003613 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003614 VK_LValue, SourceLocation());
3615
3616 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3617 // If we don't do this cast, we get the following bizarre warning/note:
3618 // xx.m:13: warning: function called through a non-compatible type
3619 // xx.m:13: note: if this code is reached, the program will abort
3620 cast = NoTypeInfoCStyleCastExpr(Context,
3621 Context->getPointerType(Context->VoidTy),
3622 CK_BitCast, DRE);
3623
3624 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003625 // If we don't have a method decl, force a variadic cast.
3626 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003627 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003628 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003629 castType = Context->getPointerType(castType);
3630 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3631 cast);
3632
3633 // Don't forget the parens to enforce the proper binding.
3634 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3635
3636 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003637 CallExpr *CE = new (Context)
3638 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003639 Stmt *ReplacingStmt = CE;
3640 if (MsgSendStretFlavor) {
3641 // We have the method which returns a struct/union. Must also generate
3642 // call to objc_msgSend_stret and hang both varieties on a conditional
3643 // expression which dictate which one to envoke depending on size of
3644 // method's return type.
3645
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003646 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3647 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003648 ArgTypes, MsgExprs,
3649 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003650 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003651 }
3652 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3653 return ReplacingStmt;
3654}
3655
3656Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3657 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3658 Exp->getLocEnd());
3659
3660 // Now do the actual rewrite.
3661 ReplaceStmt(Exp, ReplacingStmt);
3662
3663 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3664 return ReplacingStmt;
3665}
3666
3667// typedef struct objc_object Protocol;
3668QualType RewriteModernObjC::getProtocolType() {
3669 if (!ProtocolTypeDecl) {
3670 TypeSourceInfo *TInfo
3671 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3672 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3673 SourceLocation(), SourceLocation(),
3674 &Context->Idents.get("Protocol"),
3675 TInfo);
3676 }
3677 return Context->getTypeDeclType(ProtocolTypeDecl);
3678}
3679
3680/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3681/// a synthesized/forward data reference (to the protocol's metadata).
3682/// The forward references (and metadata) are generated in
3683/// RewriteModernObjC::HandleTranslationUnit().
3684Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003685 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3686 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003687 IdentifierInfo *ID = &Context->Idents.get(Name);
3688 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3689 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003690 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003691 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3692 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003693 CastExpr *castExpr =
3694 NoTypeInfoCStyleCastExpr(
3695 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003696 ReplaceStmt(Exp, castExpr);
3697 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3698 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3699 return castExpr;
3700
3701}
3702
3703bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3704 const char *endBuf) {
3705 while (startBuf < endBuf) {
3706 if (*startBuf == '#') {
3707 // Skip whitespace.
3708 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3709 ;
3710 if (!strncmp(startBuf, "if", strlen("if")) ||
3711 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3712 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3713 !strncmp(startBuf, "define", strlen("define")) ||
3714 !strncmp(startBuf, "undef", strlen("undef")) ||
3715 !strncmp(startBuf, "else", strlen("else")) ||
3716 !strncmp(startBuf, "elif", strlen("elif")) ||
3717 !strncmp(startBuf, "endif", strlen("endif")) ||
3718 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3719 !strncmp(startBuf, "include", strlen("include")) ||
3720 !strncmp(startBuf, "import", strlen("import")) ||
3721 !strncmp(startBuf, "include_next", strlen("include_next")))
3722 return true;
3723 }
3724 startBuf++;
3725 }
3726 return false;
3727}
3728
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003729/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3730/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003731bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003732 TagDecl *Tag,
3733 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003734 if (!IDecl)
3735 return false;
3736 SourceLocation TagLocation;
3737 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3738 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003739 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003740 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003741 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003742 TagLocation = RD->getLocation();
3743 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003744 IDecl->getLocation(), TagLocation);
3745 }
3746 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3747 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3748 return false;
3749 IsNamedDefinition = true;
3750 TagLocation = ED->getLocation();
3751 return Context->getSourceManager().isBeforeInTranslationUnit(
3752 IDecl->getLocation(), TagLocation);
3753
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003754 }
3755 return false;
3756}
3757
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003758/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003759/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003760bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3761 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003762 if (isa<TypedefType>(Type)) {
3763 Result += "\t";
3764 return false;
3765 }
3766
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003767 if (Type->isArrayType()) {
3768 QualType ElemTy = Context->getBaseElementType(Type);
3769 return RewriteObjCFieldDeclType(ElemTy, Result);
3770 }
3771 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003772 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3773 if (RD->isCompleteDefinition()) {
3774 if (RD->isStruct())
3775 Result += "\n\tstruct ";
3776 else if (RD->isUnion())
3777 Result += "\n\tunion ";
3778 else
3779 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003780
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003781 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003782 if (GlobalDefinedTags.count(RD)) {
3783 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003784 Result += " ";
3785 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003786 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003787 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003788 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003789 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003790 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003791 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003792 }
3793 }
3794 else if (Type->isEnumeralType()) {
3795 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3796 if (ED->isCompleteDefinition()) {
3797 Result += "\n\tenum ";
3798 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003799 if (GlobalDefinedTags.count(ED)) {
3800 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003801 Result += " ";
3802 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003803 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003804
3805 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003806 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003807 Result += "\t"; Result += EC->getName(); Result += " = ";
3808 llvm::APSInt Val = EC->getInitVal();
3809 Result += Val.toString(10);
3810 Result += ",\n";
3811 }
3812 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003813 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003814 }
3815 }
3816
3817 Result += "\t";
3818 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003819 return false;
3820}
3821
3822
3823/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3824/// It handles elaborated types, as well as enum types in the process.
3825void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3826 std::string &Result) {
3827 QualType Type = fieldDecl->getType();
3828 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003829
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003830 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3831 if (!EleboratedType)
3832 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003833 Result += Name;
3834 if (fieldDecl->isBitField()) {
3835 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3836 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003837 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003838 const ArrayType *AT = Context->getAsArrayType(Type);
3839 do {
3840 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003841 Result += "[";
3842 llvm::APInt Dim = CAT->getSize();
3843 Result += utostr(Dim.getZExtValue());
3844 Result += "]";
3845 }
Eli Friedman07bab732012-12-13 01:43:21 +00003846 AT = Context->getAsArrayType(AT->getElementType());
3847 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003848 }
3849
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003850 Result += ";\n";
3851}
3852
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003853/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3854/// named aggregate types into the input buffer.
3855void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3856 std::string &Result) {
3857 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003858 if (isa<TypedefType>(Type))
3859 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003860 if (Type->isArrayType())
3861 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003862 ObjCContainerDecl *IDecl =
3863 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003864
3865 TagDecl *TD = 0;
3866 if (Type->isRecordType()) {
3867 TD = Type->getAs<RecordType>()->getDecl();
3868 }
3869 else if (Type->isEnumeralType()) {
3870 TD = Type->getAs<EnumType>()->getDecl();
3871 }
3872
3873 if (TD) {
3874 if (GlobalDefinedTags.count(TD))
3875 return;
3876
3877 bool IsNamedDefinition = false;
3878 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3879 RewriteObjCFieldDeclType(Type, Result);
3880 Result += ";";
3881 }
3882 if (IsNamedDefinition)
3883 GlobalDefinedTags.insert(TD);
3884 }
3885
3886}
3887
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003888unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3889 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3890 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3891 return IvarGroupNumber[IV];
3892 }
3893 unsigned GroupNo = 0;
3894 SmallVector<const ObjCIvarDecl *, 8> IVars;
3895 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3896 IVD; IVD = IVD->getNextIvar())
3897 IVars.push_back(IVD);
3898
3899 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3900 if (IVars[i]->isBitField()) {
3901 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3902 while (i < e && IVars[i]->isBitField())
3903 IvarGroupNumber[IVars[i++]] = GroupNo;
3904 if (i < e)
3905 --i;
3906 }
3907
3908 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3909 return IvarGroupNumber[IV];
3910}
3911
3912QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3913 ObjCIvarDecl *IV,
3914 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3915 std::string StructTagName;
3916 ObjCIvarBitfieldGroupType(IV, StructTagName);
3917 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3918 Context->getTranslationUnitDecl(),
3919 SourceLocation(), SourceLocation(),
3920 &Context->Idents.get(StructTagName));
3921 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3922 ObjCIvarDecl *Ivar = IVars[i];
3923 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3924 &Context->Idents.get(Ivar->getName()),
3925 Ivar->getType(),
3926 0, /*Expr *BW */Ivar->getBitWidth(), false,
3927 ICIS_NoInit));
3928 }
3929 RD->completeDefinition();
3930 return Context->getTagDeclType(RD);
3931}
3932
3933QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3934 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3935 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3936 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3937 if (GroupRecordType.count(tuple))
3938 return GroupRecordType[tuple];
3939
3940 SmallVector<ObjCIvarDecl *, 8> IVars;
3941 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3942 IVD; IVD = IVD->getNextIvar()) {
3943 if (IVD->isBitField())
3944 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3945 else {
3946 if (!IVars.empty()) {
3947 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3948 // Generate the struct type for this group of bitfield ivars.
3949 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3950 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3951 IVars.clear();
3952 }
3953 }
3954 }
3955 if (!IVars.empty()) {
3956 // Do the last one.
3957 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3958 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3959 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3960 }
3961 QualType RetQT = GroupRecordType[tuple];
3962 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3963
3964 return RetQT;
3965}
3966
3967/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3968/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3969void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3970 std::string &Result) {
3971 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3972 Result += CDecl->getName();
3973 Result += "__GRBF_";
3974 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3975 Result += utostr(GroupNo);
3976 return;
3977}
3978
3979/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3980/// Name of the struct would be: classname__T_n where n is the group number for
3981/// this ivar.
3982void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3983 std::string &Result) {
3984 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3985 Result += CDecl->getName();
3986 Result += "__T_";
3987 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3988 Result += utostr(GroupNo);
3989 return;
3990}
3991
3992/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3993/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3994/// this ivar.
3995void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3996 std::string &Result) {
3997 Result += "OBJC_IVAR_$_";
3998 ObjCIvarBitfieldGroupDecl(IV, Result);
3999}
4000
4001#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4002 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4003 ++IX; \
4004 if (IX < ENDIX) \
4005 --IX; \
4006}
4007
Fariborz Jahanian11671902012-02-07 17:11:38 +00004008/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4009/// an objective-c class with ivars.
4010void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4011 std::string &Result) {
4012 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4013 assert(CDecl->getName() != "" &&
4014 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004015 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004016 SmallVector<ObjCIvarDecl *, 8> IVars;
4017 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004018 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004019 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004020
Fariborz Jahanian11671902012-02-07 17:11:38 +00004021 SourceLocation LocStart = CDecl->getLocStart();
4022 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004023
Fariborz Jahanian11671902012-02-07 17:11:38 +00004024 const char *startBuf = SM->getCharacterData(LocStart);
4025 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004026
Fariborz Jahanian11671902012-02-07 17:11:38 +00004027 // If no ivars and no root or if its root, directly or indirectly,
4028 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004029 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004030 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4031 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4032 ReplaceText(LocStart, endBuf-startBuf, Result);
4033 return;
4034 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004035
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004036 // Insert named struct/union definitions inside class to
4037 // outer scope. This follows semantics of locally defined
4038 // struct/unions in objective-c classes.
4039 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4040 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004041
4042 // Insert named structs which are syntheized to group ivar bitfields
4043 // to outer scope as well.
4044 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4045 if (IVars[i]->isBitField()) {
4046 ObjCIvarDecl *IV = IVars[i];
4047 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4048 RewriteObjCFieldDeclType(QT, Result);
4049 Result += ";";
4050 // skip over ivar bitfields in this group.
4051 SKIP_BITFIELDS(i , e, IVars);
4052 }
4053
Fariborz Jahanian11671902012-02-07 17:11:38 +00004054 Result += "\nstruct ";
4055 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004056 Result += "_IMPL {\n";
4057
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004058 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004059 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4060 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4061 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004062 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004063
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004064 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4065 if (IVars[i]->isBitField()) {
4066 ObjCIvarDecl *IV = IVars[i];
4067 Result += "\tstruct ";
4068 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4069 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4070 // skip over ivar bitfields in this group.
4071 SKIP_BITFIELDS(i , e, IVars);
4072 }
4073 else
4074 RewriteObjCFieldDecl(IVars[i], Result);
4075 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004076
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004077 Result += "};\n";
4078 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4079 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004080 // Mark this struct as having been generated.
4081 if (!ObjCSynthesizedStructs.insert(CDecl))
4082 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004083}
4084
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004085/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4086/// have been referenced in an ivar access expression.
4087void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4088 std::string &Result) {
4089 // write out ivar offset symbols which have been referenced in an ivar
4090 // access expression.
4091 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4092 if (Ivars.empty())
4093 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004094
4095 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004096 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4097 e = Ivars.end(); i != e; i++) {
4098 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004099 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4100 unsigned GroupNo = 0;
4101 if (IvarDecl->isBitField()) {
4102 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4103 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4104 continue;
4105 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004106 Result += "\n";
4107 if (LangOpts.MicrosoftExt)
4108 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004109 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004110 if (LangOpts.MicrosoftExt &&
4111 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004112 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4113 Result += "__declspec(dllimport) ";
4114
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004115 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004116 if (IvarDecl->isBitField()) {
4117 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4118 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4119 }
4120 else
4121 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004122 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004123 }
4124}
4125
Fariborz Jahanian11671902012-02-07 17:11:38 +00004126//===----------------------------------------------------------------------===//
4127// Meta Data Emission
4128//===----------------------------------------------------------------------===//
4129
4130
4131/// RewriteImplementations - This routine rewrites all method implementations
4132/// and emits meta-data.
4133
4134void RewriteModernObjC::RewriteImplementations() {
4135 int ClsDefCount = ClassImplementation.size();
4136 int CatDefCount = CategoryImplementation.size();
4137
4138 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004139 for (int i = 0; i < ClsDefCount; i++) {
4140 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4141 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4142 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004143 assert(false &&
4144 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004145 RewriteImplementationDecl(OIMP);
4146 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004147
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004148 for (int i = 0; i < CatDefCount; i++) {
4149 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4150 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4151 if (CDecl->isImplicitInterfaceDecl())
4152 assert(false &&
4153 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004154 RewriteImplementationDecl(CIMP);
4155 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004156}
4157
4158void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4159 const std::string &Name,
4160 ValueDecl *VD, bool def) {
4161 assert(BlockByRefDeclNo.count(VD) &&
4162 "RewriteByRefString: ByRef decl missing");
4163 if (def)
4164 ResultStr += "struct ";
4165 ResultStr += "__Block_byref_" + Name +
4166 "_" + utostr(BlockByRefDeclNo[VD]) ;
4167}
4168
4169static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4170 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4171 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4172 return false;
4173}
4174
4175std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4176 StringRef funcName,
4177 std::string Tag) {
4178 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004179 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004180 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004181 SourceLocation BlockLoc = CE->getExprLoc();
4182 std::string S;
4183 ConvertSourceLocationToLineDirective(BlockLoc, S);
4184
4185 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4186 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004187
4188 BlockDecl *BD = CE->getBlockDecl();
4189
4190 if (isa<FunctionNoProtoType>(AFT)) {
4191 // No user-supplied arguments. Still need to pass in a pointer to the
4192 // block (to reference imported block decl refs).
4193 S += "(" + StructRef + " *__cself)";
4194 } else if (BD->param_empty()) {
4195 S += "(" + StructRef + " *__cself)";
4196 } else {
4197 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4198 assert(FT && "SynthesizeBlockFunc: No function proto");
4199 S += '(';
4200 // first add the implicit argument.
4201 S += StructRef + " *__cself, ";
4202 std::string ParamStr;
4203 for (BlockDecl::param_iterator AI = BD->param_begin(),
4204 E = BD->param_end(); AI != E; ++AI) {
4205 if (AI != BD->param_begin()) S += ", ";
4206 ParamStr = (*AI)->getNameAsString();
4207 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004208 (void)convertBlockPointerToFunctionPointer(QT);
4209 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004210 S += ParamStr;
4211 }
4212 if (FT->isVariadic()) {
4213 if (!BD->param_empty()) S += ", ";
4214 S += "...";
4215 }
4216 S += ')';
4217 }
4218 S += " {\n";
4219
4220 // Create local declarations to avoid rewriting all closure decl ref exprs.
4221 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004222 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004223 E = BlockByRefDecls.end(); I != E; ++I) {
4224 S += " ";
4225 std::string Name = (*I)->getNameAsString();
4226 std::string TypeString;
4227 RewriteByRefString(TypeString, Name, (*I));
4228 TypeString += " *";
4229 Name = TypeString + Name;
4230 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4231 }
4232 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004233 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004234 E = BlockByCopyDecls.end(); I != E; ++I) {
4235 S += " ";
4236 // Handle nested closure invocation. For example:
4237 //
4238 // void (^myImportedClosure)(void);
4239 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4240 //
4241 // void (^anotherClosure)(void);
4242 // anotherClosure = ^(void) {
4243 // myImportedClosure(); // import and invoke the closure
4244 // };
4245 //
4246 if (isTopLevelBlockPointerType((*I)->getType())) {
4247 RewriteBlockPointerTypeVariable(S, (*I));
4248 S += " = (";
4249 RewriteBlockPointerType(S, (*I)->getType());
4250 S += ")";
4251 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4252 }
4253 else {
4254 std::string Name = (*I)->getNameAsString();
4255 QualType QT = (*I)->getType();
4256 if (HasLocalVariableExternalStorage(*I))
4257 QT = Context->getPointerType(QT);
4258 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4259 S += Name + " = __cself->" +
4260 (*I)->getNameAsString() + "; // bound by copy\n";
4261 }
4262 }
4263 std::string RewrittenStr = RewrittenBlockExprs[CE];
4264 const char *cstr = RewrittenStr.c_str();
4265 while (*cstr++ != '{') ;
4266 S += cstr;
4267 S += "\n";
4268 return S;
4269}
4270
4271std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4272 StringRef funcName,
4273 std::string Tag) {
4274 std::string StructRef = "struct " + Tag;
4275 std::string S = "static void __";
4276
4277 S += funcName;
4278 S += "_block_copy_" + utostr(i);
4279 S += "(" + StructRef;
4280 S += "*dst, " + StructRef;
4281 S += "*src) {";
4282 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4283 E = ImportedBlockDecls.end(); I != E; ++I) {
4284 ValueDecl *VD = (*I);
4285 S += "_Block_object_assign((void*)&dst->";
4286 S += (*I)->getNameAsString();
4287 S += ", (void*)src->";
4288 S += (*I)->getNameAsString();
4289 if (BlockByRefDeclsPtrSet.count((*I)))
4290 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4291 else if (VD->getType()->isBlockPointerType())
4292 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4293 else
4294 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4295 }
4296 S += "}\n";
4297
4298 S += "\nstatic void __";
4299 S += funcName;
4300 S += "_block_dispose_" + utostr(i);
4301 S += "(" + StructRef;
4302 S += "*src) {";
4303 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4304 E = ImportedBlockDecls.end(); I != E; ++I) {
4305 ValueDecl *VD = (*I);
4306 S += "_Block_object_dispose((void*)src->";
4307 S += (*I)->getNameAsString();
4308 if (BlockByRefDeclsPtrSet.count((*I)))
4309 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4310 else if (VD->getType()->isBlockPointerType())
4311 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4312 else
4313 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4314 }
4315 S += "}\n";
4316 return S;
4317}
4318
4319std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4320 std::string Desc) {
4321 std::string S = "\nstruct " + Tag;
4322 std::string Constructor = " " + Tag;
4323
4324 S += " {\n struct __block_impl impl;\n";
4325 S += " struct " + Desc;
4326 S += "* Desc;\n";
4327
4328 Constructor += "(void *fp, "; // Invoke function pointer.
4329 Constructor += "struct " + Desc; // Descriptor pointer.
4330 Constructor += " *desc";
4331
4332 if (BlockDeclRefs.size()) {
4333 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004334 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004335 E = BlockByCopyDecls.end(); I != E; ++I) {
4336 S += " ";
4337 std::string FieldName = (*I)->getNameAsString();
4338 std::string ArgName = "_" + FieldName;
4339 // Handle nested closure invocation. For example:
4340 //
4341 // void (^myImportedBlock)(void);
4342 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4343 //
4344 // void (^anotherBlock)(void);
4345 // anotherBlock = ^(void) {
4346 // myImportedBlock(); // import and invoke the closure
4347 // };
4348 //
4349 if (isTopLevelBlockPointerType((*I)->getType())) {
4350 S += "struct __block_impl *";
4351 Constructor += ", void *" + ArgName;
4352 } else {
4353 QualType QT = (*I)->getType();
4354 if (HasLocalVariableExternalStorage(*I))
4355 QT = Context->getPointerType(QT);
4356 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4357 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4358 Constructor += ", " + ArgName;
4359 }
4360 S += FieldName + ";\n";
4361 }
4362 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004363 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004364 E = BlockByRefDecls.end(); I != E; ++I) {
4365 S += " ";
4366 std::string FieldName = (*I)->getNameAsString();
4367 std::string ArgName = "_" + FieldName;
4368 {
4369 std::string TypeString;
4370 RewriteByRefString(TypeString, FieldName, (*I));
4371 TypeString += " *";
4372 FieldName = TypeString + FieldName;
4373 ArgName = TypeString + ArgName;
4374 Constructor += ", " + ArgName;
4375 }
4376 S += FieldName + "; // by ref\n";
4377 }
4378 // Finish writing the constructor.
4379 Constructor += ", int flags=0)";
4380 // Initialize all "by copy" arguments.
4381 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004382 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004383 E = BlockByCopyDecls.end(); I != E; ++I) {
4384 std::string Name = (*I)->getNameAsString();
4385 if (firsTime) {
4386 Constructor += " : ";
4387 firsTime = false;
4388 }
4389 else
4390 Constructor += ", ";
4391 if (isTopLevelBlockPointerType((*I)->getType()))
4392 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4393 else
4394 Constructor += Name + "(_" + Name + ")";
4395 }
4396 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004397 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004398 E = BlockByRefDecls.end(); I != E; ++I) {
4399 std::string Name = (*I)->getNameAsString();
4400 if (firsTime) {
4401 Constructor += " : ";
4402 firsTime = false;
4403 }
4404 else
4405 Constructor += ", ";
4406 Constructor += Name + "(_" + Name + "->__forwarding)";
4407 }
4408
4409 Constructor += " {\n";
4410 if (GlobalVarDecl)
4411 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4412 else
4413 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4414 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4415
4416 Constructor += " Desc = desc;\n";
4417 } else {
4418 // Finish writing the constructor.
4419 Constructor += ", int flags=0) {\n";
4420 if (GlobalVarDecl)
4421 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4422 else
4423 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4424 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4425 Constructor += " Desc = desc;\n";
4426 }
4427 Constructor += " ";
4428 Constructor += "}\n";
4429 S += Constructor;
4430 S += "};\n";
4431 return S;
4432}
4433
4434std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4435 std::string ImplTag, int i,
4436 StringRef FunName,
4437 unsigned hasCopy) {
4438 std::string S = "\nstatic struct " + DescTag;
4439
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004440 S += " {\n size_t reserved;\n";
4441 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004442 if (hasCopy) {
4443 S += " void (*copy)(struct ";
4444 S += ImplTag; S += "*, struct ";
4445 S += ImplTag; S += "*);\n";
4446
4447 S += " void (*dispose)(struct ";
4448 S += ImplTag; S += "*);\n";
4449 }
4450 S += "} ";
4451
4452 S += DescTag + "_DATA = { 0, sizeof(struct ";
4453 S += ImplTag + ")";
4454 if (hasCopy) {
4455 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4456 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4457 }
4458 S += "};\n";
4459 return S;
4460}
4461
4462void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4463 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004464 bool RewriteSC = (GlobalVarDecl &&
4465 !Blocks.empty() &&
4466 GlobalVarDecl->getStorageClass() == SC_Static &&
4467 GlobalVarDecl->getType().getCVRQualifiers());
4468 if (RewriteSC) {
4469 std::string SC(" void __");
4470 SC += GlobalVarDecl->getNameAsString();
4471 SC += "() {}";
4472 InsertText(FunLocStart, SC);
4473 }
4474
4475 // Insert closures that were part of the function.
4476 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4477 CollectBlockDeclRefInfo(Blocks[i]);
4478 // Need to copy-in the inner copied-in variables not actually used in this
4479 // block.
4480 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004481 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004482 ValueDecl *VD = Exp->getDecl();
4483 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004484 if (!VD->hasAttr<BlocksAttr>()) {
4485 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4486 BlockByCopyDeclsPtrSet.insert(VD);
4487 BlockByCopyDecls.push_back(VD);
4488 }
4489 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004490 }
John McCall113bee02012-03-10 09:33:50 +00004491
4492 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004493 BlockByRefDeclsPtrSet.insert(VD);
4494 BlockByRefDecls.push_back(VD);
4495 }
John McCall113bee02012-03-10 09:33:50 +00004496
Fariborz Jahanian11671902012-02-07 17:11:38 +00004497 // imported objects in the inner blocks not used in the outer
4498 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004499 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004500 VD->getType()->isBlockPointerType())
4501 ImportedBlockDecls.insert(VD);
4502 }
4503
4504 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4505 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4506
4507 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4508
4509 InsertText(FunLocStart, CI);
4510
4511 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4512
4513 InsertText(FunLocStart, CF);
4514
4515 if (ImportedBlockDecls.size()) {
4516 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4517 InsertText(FunLocStart, HF);
4518 }
4519 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4520 ImportedBlockDecls.size() > 0);
4521 InsertText(FunLocStart, BD);
4522
4523 BlockDeclRefs.clear();
4524 BlockByRefDecls.clear();
4525 BlockByRefDeclsPtrSet.clear();
4526 BlockByCopyDecls.clear();
4527 BlockByCopyDeclsPtrSet.clear();
4528 ImportedBlockDecls.clear();
4529 }
4530 if (RewriteSC) {
4531 // Must insert any 'const/volatile/static here. Since it has been
4532 // removed as result of rewriting of block literals.
4533 std::string SC;
4534 if (GlobalVarDecl->getStorageClass() == SC_Static)
4535 SC = "static ";
4536 if (GlobalVarDecl->getType().isConstQualified())
4537 SC += "const ";
4538 if (GlobalVarDecl->getType().isVolatileQualified())
4539 SC += "volatile ";
4540 if (GlobalVarDecl->getType().isRestrictQualified())
4541 SC += "restrict ";
4542 InsertText(FunLocStart, SC);
4543 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004544 if (GlobalConstructionExp) {
4545 // extra fancy dance for global literal expression.
4546
4547 // Always the latest block expression on the block stack.
4548 std::string Tag = "__";
4549 Tag += FunName;
4550 Tag += "_block_impl_";
4551 Tag += utostr(Blocks.size()-1);
4552 std::string globalBuf = "static ";
4553 globalBuf += Tag; globalBuf += " ";
4554 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004555
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004556 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004557 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004558 PrintingPolicy(LangOpts));
4559 globalBuf += constructorExprBuf.str();
4560 globalBuf += ";\n";
4561 InsertText(FunLocStart, globalBuf);
4562 GlobalConstructionExp = 0;
4563 }
4564
Fariborz Jahanian11671902012-02-07 17:11:38 +00004565 Blocks.clear();
4566 InnerDeclRefsCount.clear();
4567 InnerDeclRefs.clear();
4568 RewrittenBlockExprs.clear();
4569}
4570
4571void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004572 SourceLocation FunLocStart =
4573 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4574 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004575 StringRef FuncName = FD->getName();
4576
4577 SynthesizeBlockLiterals(FunLocStart, FuncName);
4578}
4579
4580static void BuildUniqueMethodName(std::string &Name,
4581 ObjCMethodDecl *MD) {
4582 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4583 Name = IFace->getName();
4584 Name += "__" + MD->getSelector().getAsString();
4585 // Convert colons to underscores.
4586 std::string::size_type loc = 0;
4587 while ((loc = Name.find(":", loc)) != std::string::npos)
4588 Name.replace(loc, 1, "_");
4589}
4590
4591void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4592 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4593 //SourceLocation FunLocStart = MD->getLocStart();
4594 SourceLocation FunLocStart = MD->getLocStart();
4595 std::string FuncName;
4596 BuildUniqueMethodName(FuncName, MD);
4597 SynthesizeBlockLiterals(FunLocStart, FuncName);
4598}
4599
4600void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4601 for (Stmt::child_range CI = S->children(); CI; ++CI)
4602 if (*CI) {
4603 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4604 GetBlockDeclRefExprs(CBE->getBody());
4605 else
4606 GetBlockDeclRefExprs(*CI);
4607 }
4608 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004609 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4610 if (DRE->refersToEnclosingLocal()) {
4611 // FIXME: Handle enums.
4612 if (!isa<FunctionDecl>(DRE->getDecl()))
4613 BlockDeclRefs.push_back(DRE);
4614 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4615 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004616 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004617 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004618
4619 return;
4620}
4621
Craig Topper5603df42013-07-05 19:34:19 +00004622void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4623 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004624 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4625 for (Stmt::child_range CI = S->children(); CI; ++CI)
4626 if (*CI) {
4627 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4628 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4629 GetInnerBlockDeclRefExprs(CBE->getBody(),
4630 InnerBlockDeclRefs,
4631 InnerContexts);
4632 }
4633 else
4634 GetInnerBlockDeclRefExprs(*CI,
4635 InnerBlockDeclRefs,
4636 InnerContexts);
4637
4638 }
4639 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004640 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4641 if (DRE->refersToEnclosingLocal()) {
4642 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4643 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4644 InnerBlockDeclRefs.push_back(DRE);
4645 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4646 if (Var->isFunctionOrMethodVarDecl())
4647 ImportedLocalExternalDecls.insert(Var);
4648 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004649 }
4650
4651 return;
4652}
4653
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004654/// convertObjCTypeToCStyleType - This routine converts such objc types
4655/// as qualified objects, and blocks to their closest c/c++ types that
4656/// it can. It returns true if input type was modified.
4657bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4658 QualType oldT = T;
4659 convertBlockPointerToFunctionPointer(T);
4660 if (T->isFunctionPointerType()) {
4661 QualType PointeeTy;
4662 if (const PointerType* PT = T->getAs<PointerType>()) {
4663 PointeeTy = PT->getPointeeType();
4664 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4665 T = convertFunctionTypeOfBlocks(FT);
4666 T = Context->getPointerType(T);
4667 }
4668 }
4669 }
4670
4671 convertToUnqualifiedObjCType(T);
4672 return T != oldT;
4673}
4674
Fariborz Jahanian11671902012-02-07 17:11:38 +00004675/// convertFunctionTypeOfBlocks - This routine converts a function type
4676/// whose result type may be a block pointer or whose argument type(s)
4677/// might be block pointers to an equivalent function type replacing
4678/// all block pointers to function pointers.
4679QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4680 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4681 // FTP will be null for closures that don't take arguments.
4682 // Generate a funky cast.
4683 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004684 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004685 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004686
4687 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004688 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4689 E = FTP->param_type_end();
4690 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004691 QualType t = *I;
4692 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004693 if (convertObjCTypeToCStyleType(t))
4694 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004695 ArgTypes.push_back(t);
4696 }
4697 }
4698 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004699 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004700 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004701 else FuncType = QualType(FT, 0);
4702 return FuncType;
4703}
4704
4705Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4706 // Navigate to relevant type information.
4707 const BlockPointerType *CPT = 0;
4708
4709 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4710 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004711 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4712 CPT = MExpr->getType()->getAs<BlockPointerType>();
4713 }
4714 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4715 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4716 }
4717 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4718 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4719 else if (const ConditionalOperator *CEXPR =
4720 dyn_cast<ConditionalOperator>(BlockExp)) {
4721 Expr *LHSExp = CEXPR->getLHS();
4722 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4723 Expr *RHSExp = CEXPR->getRHS();
4724 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4725 Expr *CONDExp = CEXPR->getCond();
4726 ConditionalOperator *CondExpr =
4727 new (Context) ConditionalOperator(CONDExp,
4728 SourceLocation(), cast<Expr>(LHSStmt),
4729 SourceLocation(), cast<Expr>(RHSStmt),
4730 Exp->getType(), VK_RValue, OK_Ordinary);
4731 return CondExpr;
4732 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4733 CPT = IRE->getType()->getAs<BlockPointerType>();
4734 } else if (const PseudoObjectExpr *POE
4735 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4736 CPT = POE->getType()->castAs<BlockPointerType>();
4737 } else {
4738 assert(1 && "RewriteBlockClass: Bad type");
4739 }
4740 assert(CPT && "RewriteBlockClass: Bad type");
4741 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4742 assert(FT && "RewriteBlockClass: Bad type");
4743 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4744 // FTP will be null for closures that don't take arguments.
4745
4746 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4747 SourceLocation(), SourceLocation(),
4748 &Context->Idents.get("__block_impl"));
4749 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4750
4751 // Generate a funky cast.
4752 SmallVector<QualType, 8> ArgTypes;
4753
4754 // Push the block argument type.
4755 ArgTypes.push_back(PtrBlock);
4756 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004757 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4758 E = FTP->param_type_end();
4759 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004760 QualType t = *I;
4761 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4762 if (!convertBlockPointerToFunctionPointer(t))
4763 convertToUnqualifiedObjCType(t);
4764 ArgTypes.push_back(t);
4765 }
4766 }
4767 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004768 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004769
4770 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4771
4772 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4773 CK_BitCast,
4774 const_cast<Expr*>(BlockExp));
4775 // Don't forget the parens to enforce the proper binding.
4776 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4777 BlkCast);
4778 //PE->dump();
4779
4780 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4781 SourceLocation(),
4782 &Context->Idents.get("FuncPtr"),
4783 Context->VoidPtrTy, 0,
4784 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004785 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004786 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4787 FD->getType(), VK_LValue,
4788 OK_Ordinary);
4789
4790
4791 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4792 CK_BitCast, ME);
4793 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4794
4795 SmallVector<Expr*, 8> BlkExprs;
4796 // Add the implicit argument.
4797 BlkExprs.push_back(BlkCast);
4798 // Add the user arguments.
4799 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4800 E = Exp->arg_end(); I != E; ++I) {
4801 BlkExprs.push_back(*I);
4802 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004803 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004804 Exp->getType(), VK_RValue,
4805 SourceLocation());
4806 return CE;
4807}
4808
4809// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004810// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004811// For example:
4812//
4813// int main() {
4814// __block Foo *f;
4815// __block int i;
4816//
4817// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004818// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004819// i = 77;
4820// };
4821//}
John McCall113bee02012-03-10 09:33:50 +00004822Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004823 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4824 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004825 ValueDecl *VD = DeclRefExp->getDecl();
4826 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004827
4828 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4829 SourceLocation(),
4830 &Context->Idents.get("__forwarding"),
4831 Context->VoidPtrTy, 0,
4832 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004833 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004834 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4835 FD, SourceLocation(),
4836 FD->getType(), VK_LValue,
4837 OK_Ordinary);
4838
4839 StringRef Name = VD->getName();
4840 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4841 &Context->Idents.get(Name),
4842 Context->VoidPtrTy, 0,
4843 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004844 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004845 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4846 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4847
4848
4849
4850 // Need parens to enforce precedence.
4851 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4852 DeclRefExp->getExprLoc(),
4853 ME);
4854 ReplaceStmt(DeclRefExp, PE);
4855 return PE;
4856}
4857
4858// Rewrites the imported local variable V with external storage
4859// (static, extern, etc.) as *V
4860//
4861Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4862 ValueDecl *VD = DRE->getDecl();
4863 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4864 if (!ImportedLocalExternalDecls.count(Var))
4865 return DRE;
4866 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4867 VK_LValue, OK_Ordinary,
4868 DRE->getLocation());
4869 // Need parens to enforce precedence.
4870 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4871 Exp);
4872 ReplaceStmt(DRE, PE);
4873 return PE;
4874}
4875
4876void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4877 SourceLocation LocStart = CE->getLParenLoc();
4878 SourceLocation LocEnd = CE->getRParenLoc();
4879
4880 // Need to avoid trying to rewrite synthesized casts.
4881 if (LocStart.isInvalid())
4882 return;
4883 // Need to avoid trying to rewrite casts contained in macros.
4884 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4885 return;
4886
4887 const char *startBuf = SM->getCharacterData(LocStart);
4888 const char *endBuf = SM->getCharacterData(LocEnd);
4889 QualType QT = CE->getType();
4890 const Type* TypePtr = QT->getAs<Type>();
4891 if (isa<TypeOfExprType>(TypePtr)) {
4892 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4893 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4894 std::string TypeAsString = "(";
4895 RewriteBlockPointerType(TypeAsString, QT);
4896 TypeAsString += ")";
4897 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4898 return;
4899 }
4900 // advance the location to startArgList.
4901 const char *argPtr = startBuf;
4902
4903 while (*argPtr++ && (argPtr < endBuf)) {
4904 switch (*argPtr) {
4905 case '^':
4906 // Replace the '^' with '*'.
4907 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4908 ReplaceText(LocStart, 1, "*");
4909 break;
4910 }
4911 }
4912 return;
4913}
4914
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004915void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4916 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004917 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4918 CastKind != CK_AnyPointerToBlockPointerCast)
4919 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004920
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004921 QualType QT = IC->getType();
4922 (void)convertBlockPointerToFunctionPointer(QT);
4923 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4924 std::string Str = "(";
4925 Str += TypeString;
4926 Str += ")";
4927 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4928
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004929 return;
4930}
4931
Fariborz Jahanian11671902012-02-07 17:11:38 +00004932void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4933 SourceLocation DeclLoc = FD->getLocation();
4934 unsigned parenCount = 0;
4935
4936 // We have 1 or more arguments that have closure pointers.
4937 const char *startBuf = SM->getCharacterData(DeclLoc);
4938 const char *startArgList = strchr(startBuf, '(');
4939
4940 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4941
4942 parenCount++;
4943 // advance the location to startArgList.
4944 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4945 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4946
4947 const char *argPtr = startArgList;
4948
4949 while (*argPtr++ && parenCount) {
4950 switch (*argPtr) {
4951 case '^':
4952 // Replace the '^' with '*'.
4953 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4954 ReplaceText(DeclLoc, 1, "*");
4955 break;
4956 case '(':
4957 parenCount++;
4958 break;
4959 case ')':
4960 parenCount--;
4961 break;
4962 }
4963 }
4964 return;
4965}
4966
4967bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4968 const FunctionProtoType *FTP;
4969 const PointerType *PT = QT->getAs<PointerType>();
4970 if (PT) {
4971 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4972 } else {
4973 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4974 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4975 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4976 }
4977 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004978 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4979 E = FTP->param_type_end();
4980 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004981 if (isTopLevelBlockPointerType(*I))
4982 return true;
4983 }
4984 return false;
4985}
4986
4987bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4988 const FunctionProtoType *FTP;
4989 const PointerType *PT = QT->getAs<PointerType>();
4990 if (PT) {
4991 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4992 } else {
4993 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4994 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4995 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4996 }
4997 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004998 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4999 E = FTP->param_type_end();
5000 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005001 if ((*I)->isObjCQualifiedIdType())
5002 return true;
5003 if ((*I)->isObjCObjectPointerType() &&
5004 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5005 return true;
5006 }
5007
5008 }
5009 return false;
5010}
5011
5012void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5013 const char *&RParen) {
5014 const char *argPtr = strchr(Name, '(');
5015 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5016
5017 LParen = argPtr; // output the start.
5018 argPtr++; // skip past the left paren.
5019 unsigned parenCount = 1;
5020
5021 while (*argPtr && parenCount) {
5022 switch (*argPtr) {
5023 case '(': parenCount++; break;
5024 case ')': parenCount--; break;
5025 default: break;
5026 }
5027 if (parenCount) argPtr++;
5028 }
5029 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5030 RParen = argPtr; // output the end
5031}
5032
5033void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5034 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5035 RewriteBlockPointerFunctionArgs(FD);
5036 return;
5037 }
5038 // Handle Variables and Typedefs.
5039 SourceLocation DeclLoc = ND->getLocation();
5040 QualType DeclT;
5041 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5042 DeclT = VD->getType();
5043 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5044 DeclT = TDD->getUnderlyingType();
5045 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5046 DeclT = FD->getType();
5047 else
5048 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5049
5050 const char *startBuf = SM->getCharacterData(DeclLoc);
5051 const char *endBuf = startBuf;
5052 // scan backward (from the decl location) for the end of the previous decl.
5053 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5054 startBuf--;
5055 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5056 std::string buf;
5057 unsigned OrigLength=0;
5058 // *startBuf != '^' if we are dealing with a pointer to function that
5059 // may take block argument types (which will be handled below).
5060 if (*startBuf == '^') {
5061 // Replace the '^' with '*', computing a negative offset.
5062 buf = '*';
5063 startBuf++;
5064 OrigLength++;
5065 }
5066 while (*startBuf != ')') {
5067 buf += *startBuf;
5068 startBuf++;
5069 OrigLength++;
5070 }
5071 buf += ')';
5072 OrigLength++;
5073
5074 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5075 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5076 // Replace the '^' with '*' for arguments.
5077 // Replace id<P> with id/*<>*/
5078 DeclLoc = ND->getLocation();
5079 startBuf = SM->getCharacterData(DeclLoc);
5080 const char *argListBegin, *argListEnd;
5081 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5082 while (argListBegin < argListEnd) {
5083 if (*argListBegin == '^')
5084 buf += '*';
5085 else if (*argListBegin == '<') {
5086 buf += "/*";
5087 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005088 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005089 while (*argListBegin != '>') {
5090 buf += *argListBegin++;
5091 OrigLength++;
5092 }
5093 buf += *argListBegin;
5094 buf += "*/";
5095 }
5096 else
5097 buf += *argListBegin;
5098 argListBegin++;
5099 OrigLength++;
5100 }
5101 buf += ')';
5102 OrigLength++;
5103 }
5104 ReplaceText(Start, OrigLength, buf);
5105
5106 return;
5107}
5108
5109
5110/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5111/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5112/// struct Block_byref_id_object *src) {
5113/// _Block_object_assign (&_dest->object, _src->object,
5114/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5115/// [|BLOCK_FIELD_IS_WEAK]) // object
5116/// _Block_object_assign(&_dest->object, _src->object,
5117/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5118/// [|BLOCK_FIELD_IS_WEAK]) // block
5119/// }
5120/// And:
5121/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5122/// _Block_object_dispose(_src->object,
5123/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5124/// [|BLOCK_FIELD_IS_WEAK]) // object
5125/// _Block_object_dispose(_src->object,
5126/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5127/// [|BLOCK_FIELD_IS_WEAK]) // block
5128/// }
5129
5130std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5131 int flag) {
5132 std::string S;
5133 if (CopyDestroyCache.count(flag))
5134 return S;
5135 CopyDestroyCache.insert(flag);
5136 S = "static void __Block_byref_id_object_copy_";
5137 S += utostr(flag);
5138 S += "(void *dst, void *src) {\n";
5139
5140 // offset into the object pointer is computed as:
5141 // void * + void* + int + int + void* + void *
5142 unsigned IntSize =
5143 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5144 unsigned VoidPtrSize =
5145 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5146
5147 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5148 S += " _Block_object_assign((char*)dst + ";
5149 S += utostr(offset);
5150 S += ", *(void * *) ((char*)src + ";
5151 S += utostr(offset);
5152 S += "), ";
5153 S += utostr(flag);
5154 S += ");\n}\n";
5155
5156 S += "static void __Block_byref_id_object_dispose_";
5157 S += utostr(flag);
5158 S += "(void *src) {\n";
5159 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5160 S += utostr(offset);
5161 S += "), ";
5162 S += utostr(flag);
5163 S += ");\n}\n";
5164 return S;
5165}
5166
5167/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5168/// the declaration into:
5169/// struct __Block_byref_ND {
5170/// void *__isa; // NULL for everything except __weak pointers
5171/// struct __Block_byref_ND *__forwarding;
5172/// int32_t __flags;
5173/// int32_t __size;
5174/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5175/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5176/// typex ND;
5177/// };
5178///
5179/// It then replaces declaration of ND variable with:
5180/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5181/// __size=sizeof(struct __Block_byref_ND),
5182/// ND=initializer-if-any};
5183///
5184///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005185void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5186 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005187 int flag = 0;
5188 int isa = 0;
5189 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5190 if (DeclLoc.isInvalid())
5191 // If type location is missing, it is because of missing type (a warning).
5192 // Use variable's location which is good for this case.
5193 DeclLoc = ND->getLocation();
5194 const char *startBuf = SM->getCharacterData(DeclLoc);
5195 SourceLocation X = ND->getLocEnd();
5196 X = SM->getExpansionLoc(X);
5197 const char *endBuf = SM->getCharacterData(X);
5198 std::string Name(ND->getNameAsString());
5199 std::string ByrefType;
5200 RewriteByRefString(ByrefType, Name, ND, true);
5201 ByrefType += " {\n";
5202 ByrefType += " void *__isa;\n";
5203 RewriteByRefString(ByrefType, Name, ND);
5204 ByrefType += " *__forwarding;\n";
5205 ByrefType += " int __flags;\n";
5206 ByrefType += " int __size;\n";
5207 // Add void *__Block_byref_id_object_copy;
5208 // void *__Block_byref_id_object_dispose; if needed.
5209 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005210 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005211 if (HasCopyAndDispose) {
5212 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5213 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5214 }
5215
5216 QualType T = Ty;
5217 (void)convertBlockPointerToFunctionPointer(T);
5218 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5219
5220 ByrefType += " " + Name + ";\n";
5221 ByrefType += "};\n";
5222 // Insert this type in global scope. It is needed by helper function.
5223 SourceLocation FunLocStart;
5224 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005225 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005226 else {
5227 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5228 FunLocStart = CurMethodDef->getLocStart();
5229 }
5230 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005231
Fariborz Jahanian11671902012-02-07 17:11:38 +00005232 if (Ty.isObjCGCWeak()) {
5233 flag |= BLOCK_FIELD_IS_WEAK;
5234 isa = 1;
5235 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005236 if (HasCopyAndDispose) {
5237 flag = BLOCK_BYREF_CALLER;
5238 QualType Ty = ND->getType();
5239 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5240 if (Ty->isBlockPointerType())
5241 flag |= BLOCK_FIELD_IS_BLOCK;
5242 else
5243 flag |= BLOCK_FIELD_IS_OBJECT;
5244 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5245 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005246 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005247 }
5248
5249 // struct __Block_byref_ND ND =
5250 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5251 // initializer-if-any};
5252 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005253 // FIXME. rewriter does not support __block c++ objects which
5254 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005255 if (hasInit)
5256 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5257 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5258 if (CXXDecl && CXXDecl->isDefaultConstructor())
5259 hasInit = false;
5260 }
5261
Fariborz Jahanian11671902012-02-07 17:11:38 +00005262 unsigned flags = 0;
5263 if (HasCopyAndDispose)
5264 flags |= BLOCK_HAS_COPY_DISPOSE;
5265 Name = ND->getNameAsString();
5266 ByrefType.clear();
5267 RewriteByRefString(ByrefType, Name, ND);
5268 std::string ForwardingCastType("(");
5269 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005270 ByrefType += " " + Name + " = {(void*)";
5271 ByrefType += utostr(isa);
5272 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5273 ByrefType += utostr(flags);
5274 ByrefType += ", ";
5275 ByrefType += "sizeof(";
5276 RewriteByRefString(ByrefType, Name, ND);
5277 ByrefType += ")";
5278 if (HasCopyAndDispose) {
5279 ByrefType += ", __Block_byref_id_object_copy_";
5280 ByrefType += utostr(flag);
5281 ByrefType += ", __Block_byref_id_object_dispose_";
5282 ByrefType += utostr(flag);
5283 }
5284
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005285 if (!firstDecl) {
5286 // In multiple __block declarations, and for all but 1st declaration,
5287 // find location of the separating comma. This would be start location
5288 // where new text is to be inserted.
5289 DeclLoc = ND->getLocation();
5290 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5291 const char *commaBuf = startDeclBuf;
5292 while (*commaBuf != ',')
5293 commaBuf--;
5294 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5295 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5296 startBuf = commaBuf;
5297 }
5298
Fariborz Jahanian11671902012-02-07 17:11:38 +00005299 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005300 ByrefType += "};\n";
5301 unsigned nameSize = Name.size();
5302 // for block or function pointer declaration. Name is aleady
5303 // part of the declaration.
5304 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5305 nameSize = 1;
5306 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5307 }
5308 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005309 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005310 SourceLocation startLoc;
5311 Expr *E = ND->getInit();
5312 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5313 startLoc = ECE->getLParenLoc();
5314 else
5315 startLoc = E->getLocStart();
5316 startLoc = SM->getExpansionLoc(startLoc);
5317 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005318 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005319
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005320 const char separator = lastDecl ? ';' : ',';
5321 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5322 const char *separatorBuf = strchr(startInitializerBuf, separator);
5323 assert((*separatorBuf == separator) &&
5324 "RewriteByRefVar: can't find ';' or ','");
5325 SourceLocation separatorLoc =
5326 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5327
5328 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005329 }
5330 return;
5331}
5332
5333void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5334 // Add initializers for any closure decl refs.
5335 GetBlockDeclRefExprs(Exp->getBody());
5336 if (BlockDeclRefs.size()) {
5337 // Unique all "by copy" declarations.
5338 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005339 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005340 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5341 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5342 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5343 }
5344 }
5345 // Unique all "by ref" declarations.
5346 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005347 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005348 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5349 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5350 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5351 }
5352 }
5353 // Find any imported blocks...they will need special attention.
5354 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005355 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005356 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5357 BlockDeclRefs[i]->getType()->isBlockPointerType())
5358 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5359 }
5360}
5361
5362FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5363 IdentifierInfo *ID = &Context->Idents.get(name);
5364 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5365 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5366 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005367 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005368}
5369
5370Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005371 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005372
Fariborz Jahanian11671902012-02-07 17:11:38 +00005373 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005374
Fariborz Jahanian11671902012-02-07 17:11:38 +00005375 Blocks.push_back(Exp);
5376
5377 CollectBlockDeclRefInfo(Exp);
5378
5379 // Add inner imported variables now used in current block.
5380 int countOfInnerDecls = 0;
5381 if (!InnerBlockDeclRefs.empty()) {
5382 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005383 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005384 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005385 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005386 // We need to save the copied-in variables in nested
5387 // blocks because it is needed at the end for some of the API generations.
5388 // See SynthesizeBlockLiterals routine.
5389 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5390 BlockDeclRefs.push_back(Exp);
5391 BlockByCopyDeclsPtrSet.insert(VD);
5392 BlockByCopyDecls.push_back(VD);
5393 }
John McCall113bee02012-03-10 09:33:50 +00005394 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005395 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5396 BlockDeclRefs.push_back(Exp);
5397 BlockByRefDeclsPtrSet.insert(VD);
5398 BlockByRefDecls.push_back(VD);
5399 }
5400 }
5401 // Find any imported blocks...they will need special attention.
5402 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005403 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005404 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5405 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5406 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5407 }
5408 InnerDeclRefsCount.push_back(countOfInnerDecls);
5409
5410 std::string FuncName;
5411
5412 if (CurFunctionDef)
5413 FuncName = CurFunctionDef->getNameAsString();
5414 else if (CurMethodDef)
5415 BuildUniqueMethodName(FuncName, CurMethodDef);
5416 else if (GlobalVarDecl)
5417 FuncName = std::string(GlobalVarDecl->getNameAsString());
5418
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005419 bool GlobalBlockExpr =
5420 block->getDeclContext()->getRedeclContext()->isFileContext();
5421
5422 if (GlobalBlockExpr && !GlobalVarDecl) {
5423 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5424 GlobalBlockExpr = false;
5425 }
5426
Fariborz Jahanian11671902012-02-07 17:11:38 +00005427 std::string BlockNumber = utostr(Blocks.size()-1);
5428
Fariborz Jahanian11671902012-02-07 17:11:38 +00005429 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5430
5431 // Get a pointer to the function type so we can cast appropriately.
5432 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5433 QualType FType = Context->getPointerType(BFT);
5434
5435 FunctionDecl *FD;
5436 Expr *NewRep;
5437
Benjamin Kramer60509af2013-09-09 14:48:42 +00005438 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005439 std::string Tag;
5440
5441 if (GlobalBlockExpr)
5442 Tag = "__global_";
5443 else
5444 Tag = "__";
5445 Tag += FuncName + "_block_impl_" + BlockNumber;
5446
Fariborz Jahanian11671902012-02-07 17:11:38 +00005447 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005448 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005449 SourceLocation());
5450
5451 SmallVector<Expr*, 4> InitExprs;
5452
5453 // Initialize the block function.
5454 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005455 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5456 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005457 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5458 CK_BitCast, Arg);
5459 InitExprs.push_back(castExpr);
5460
5461 // Initialize the block descriptor.
5462 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5463
5464 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5465 SourceLocation(), SourceLocation(),
5466 &Context->Idents.get(DescData.c_str()),
5467 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005468 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005469 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005470 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005471 Context->VoidPtrTy,
5472 VK_LValue,
5473 SourceLocation()),
5474 UO_AddrOf,
5475 Context->getPointerType(Context->VoidPtrTy),
5476 VK_RValue, OK_Ordinary,
5477 SourceLocation());
5478 InitExprs.push_back(DescRefExpr);
5479
5480 // Add initializers for any closure decl refs.
5481 if (BlockDeclRefs.size()) {
5482 Expr *Exp;
5483 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005484 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005485 E = BlockByCopyDecls.end(); I != E; ++I) {
5486 if (isObjCType((*I)->getType())) {
5487 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5488 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005489 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5490 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005491 if (HasLocalVariableExternalStorage(*I)) {
5492 QualType QT = (*I)->getType();
5493 QT = Context->getPointerType(QT);
5494 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5495 OK_Ordinary, SourceLocation());
5496 }
5497 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5498 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005499 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5500 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005501 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5502 CK_BitCast, Arg);
5503 } else {
5504 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005505 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5506 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005507 if (HasLocalVariableExternalStorage(*I)) {
5508 QualType QT = (*I)->getType();
5509 QT = Context->getPointerType(QT);
5510 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5511 OK_Ordinary, SourceLocation());
5512 }
5513
5514 }
5515 InitExprs.push_back(Exp);
5516 }
5517 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005518 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005519 E = BlockByRefDecls.end(); I != E; ++I) {
5520 ValueDecl *ND = (*I);
5521 std::string Name(ND->getNameAsString());
5522 std::string RecName;
5523 RewriteByRefString(RecName, Name, ND, true);
5524 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5525 + sizeof("struct"));
5526 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5527 SourceLocation(), SourceLocation(),
5528 II);
5529 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5530 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5531
5532 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005533 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005534 SourceLocation());
5535 bool isNestedCapturedVar = false;
5536 if (block)
5537 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5538 ce = block->capture_end(); ci != ce; ++ci) {
5539 const VarDecl *variable = ci->getVariable();
5540 if (variable == ND && ci->isNested()) {
5541 assert (ci->isByRef() &&
5542 "SynthBlockInitExpr - captured block variable is not byref");
5543 isNestedCapturedVar = true;
5544 break;
5545 }
5546 }
5547 // captured nested byref variable has its address passed. Do not take
5548 // its address again.
5549 if (!isNestedCapturedVar)
5550 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5551 Context->getPointerType(Exp->getType()),
5552 VK_RValue, OK_Ordinary, SourceLocation());
5553 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5554 InitExprs.push_back(Exp);
5555 }
5556 }
5557 if (ImportedBlockDecls.size()) {
5558 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5559 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5560 unsigned IntSize =
5561 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5562 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5563 Context->IntTy, SourceLocation());
5564 InitExprs.push_back(FlagExp);
5565 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005566 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005567 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005568
5569 if (GlobalBlockExpr) {
5570 assert (GlobalConstructionExp == 0 &&
5571 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5572 GlobalConstructionExp = NewRep;
5573 NewRep = DRE;
5574 }
5575
Fariborz Jahanian11671902012-02-07 17:11:38 +00005576 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5577 Context->getPointerType(NewRep->getType()),
5578 VK_RValue, OK_Ordinary, SourceLocation());
5579 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5580 NewRep);
5581 BlockDeclRefs.clear();
5582 BlockByRefDecls.clear();
5583 BlockByRefDeclsPtrSet.clear();
5584 BlockByCopyDecls.clear();
5585 BlockByCopyDeclsPtrSet.clear();
5586 ImportedBlockDecls.clear();
5587 return NewRep;
5588}
5589
5590bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5591 if (const ObjCForCollectionStmt * CS =
5592 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5593 return CS->getElement() == DS;
5594 return false;
5595}
5596
5597//===----------------------------------------------------------------------===//
5598// Function Body / Expression rewriting
5599//===----------------------------------------------------------------------===//
5600
5601Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5602 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5603 isa<DoStmt>(S) || isa<ForStmt>(S))
5604 Stmts.push_back(S);
5605 else if (isa<ObjCForCollectionStmt>(S)) {
5606 Stmts.push_back(S);
5607 ObjCBcLabelNo.push_back(++BcLabelCount);
5608 }
5609
5610 // Pseudo-object operations and ivar references need special
5611 // treatment because we're going to recursively rewrite them.
5612 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5613 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5614 return RewritePropertyOrImplicitSetter(PseudoOp);
5615 } else {
5616 return RewritePropertyOrImplicitGetter(PseudoOp);
5617 }
5618 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5619 return RewriteObjCIvarRefExpr(IvarRefExpr);
5620 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005621 else if (isa<OpaqueValueExpr>(S))
5622 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005623
5624 SourceRange OrigStmtRange = S->getSourceRange();
5625
5626 // Perform a bottom up rewrite of all children.
5627 for (Stmt::child_range CI = S->children(); CI; ++CI)
5628 if (*CI) {
5629 Stmt *childStmt = (*CI);
5630 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5631 if (newStmt) {
5632 *CI = newStmt;
5633 }
5634 }
5635
5636 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005637 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005638 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5639 InnerContexts.insert(BE->getBlockDecl());
5640 ImportedLocalExternalDecls.clear();
5641 GetInnerBlockDeclRefExprs(BE->getBody(),
5642 InnerBlockDeclRefs, InnerContexts);
5643 // Rewrite the block body in place.
5644 Stmt *SaveCurrentBody = CurrentBody;
5645 CurrentBody = BE->getBody();
5646 PropParentMap = 0;
5647 // block literal on rhs of a property-dot-sytax assignment
5648 // must be replaced by its synthesize ast so getRewrittenText
5649 // works as expected. In this case, what actually ends up on RHS
5650 // is the blockTranscribed which is the helper function for the
5651 // block literal; as in: self.c = ^() {[ace ARR];};
5652 bool saveDisableReplaceStmt = DisableReplaceStmt;
5653 DisableReplaceStmt = false;
5654 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5655 DisableReplaceStmt = saveDisableReplaceStmt;
5656 CurrentBody = SaveCurrentBody;
5657 PropParentMap = 0;
5658 ImportedLocalExternalDecls.clear();
5659 // Now we snarf the rewritten text and stash it away for later use.
5660 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5661 RewrittenBlockExprs[BE] = Str;
5662
5663 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5664
5665 //blockTranscribed->dump();
5666 ReplaceStmt(S, blockTranscribed);
5667 return blockTranscribed;
5668 }
5669 // Handle specific things.
5670 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5671 return RewriteAtEncode(AtEncode);
5672
5673 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5674 return RewriteAtSelector(AtSelector);
5675
5676 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5677 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005678
5679 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5680 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005681
Patrick Beard0caa3942012-04-19 00:25:12 +00005682 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5683 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005684
5685 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5686 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005687
5688 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5689 dyn_cast<ObjCDictionaryLiteral>(S))
5690 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005691
5692 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5693#if 0
5694 // Before we rewrite it, put the original message expression in a comment.
5695 SourceLocation startLoc = MessExpr->getLocStart();
5696 SourceLocation endLoc = MessExpr->getLocEnd();
5697
5698 const char *startBuf = SM->getCharacterData(startLoc);
5699 const char *endBuf = SM->getCharacterData(endLoc);
5700
5701 std::string messString;
5702 messString += "// ";
5703 messString.append(startBuf, endBuf-startBuf+1);
5704 messString += "\n";
5705
5706 // FIXME: Missing definition of
5707 // InsertText(clang::SourceLocation, char const*, unsigned int).
5708 // InsertText(startLoc, messString.c_str(), messString.size());
5709 // Tried this, but it didn't work either...
5710 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5711#endif
5712 return RewriteMessageExpr(MessExpr);
5713 }
5714
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005715 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5716 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5717 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5718 }
5719
Fariborz Jahanian11671902012-02-07 17:11:38 +00005720 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5721 return RewriteObjCTryStmt(StmtTry);
5722
5723 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5724 return RewriteObjCSynchronizedStmt(StmtTry);
5725
5726 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5727 return RewriteObjCThrowStmt(StmtThrow);
5728
5729 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5730 return RewriteObjCProtocolExpr(ProtocolExp);
5731
5732 if (ObjCForCollectionStmt *StmtForCollection =
5733 dyn_cast<ObjCForCollectionStmt>(S))
5734 return RewriteObjCForCollectionStmt(StmtForCollection,
5735 OrigStmtRange.getEnd());
5736 if (BreakStmt *StmtBreakStmt =
5737 dyn_cast<BreakStmt>(S))
5738 return RewriteBreakStmt(StmtBreakStmt);
5739 if (ContinueStmt *StmtContinueStmt =
5740 dyn_cast<ContinueStmt>(S))
5741 return RewriteContinueStmt(StmtContinueStmt);
5742
5743 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5744 // and cast exprs.
5745 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5746 // FIXME: What we're doing here is modifying the type-specifier that
5747 // precedes the first Decl. In the future the DeclGroup should have
5748 // a separate type-specifier that we can rewrite.
5749 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5750 // the context of an ObjCForCollectionStmt. For example:
5751 // NSArray *someArray;
5752 // for (id <FooProtocol> index in someArray) ;
5753 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5754 // and it depends on the original text locations/positions.
5755 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5756 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5757
5758 // Blocks rewrite rules.
5759 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5760 DI != DE; ++DI) {
5761 Decl *SD = *DI;
5762 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5763 if (isTopLevelBlockPointerType(ND->getType()))
5764 RewriteBlockPointerDecl(ND);
5765 else if (ND->getType()->isFunctionPointerType())
5766 CheckFunctionPointerDecl(ND->getType(), ND);
5767 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5768 if (VD->hasAttr<BlocksAttr>()) {
5769 static unsigned uniqueByrefDeclCount = 0;
5770 assert(!BlockByRefDeclNo.count(ND) &&
5771 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5772 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005773 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005774 }
5775 else
5776 RewriteTypeOfDecl(VD);
5777 }
5778 }
5779 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5780 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5781 RewriteBlockPointerDecl(TD);
5782 else if (TD->getUnderlyingType()->isFunctionPointerType())
5783 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5784 }
5785 }
5786 }
5787
5788 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5789 RewriteObjCQualifiedInterfaceTypes(CE);
5790
5791 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5792 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5793 assert(!Stmts.empty() && "Statement stack is empty");
5794 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5795 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5796 && "Statement stack mismatch");
5797 Stmts.pop_back();
5798 }
5799 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005800 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5801 ValueDecl *VD = DRE->getDecl();
5802 if (VD->hasAttr<BlocksAttr>())
5803 return RewriteBlockDeclRefExpr(DRE);
5804 if (HasLocalVariableExternalStorage(VD))
5805 return RewriteLocalVariableExternalStorage(DRE);
5806 }
5807
5808 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5809 if (CE->getCallee()->getType()->isBlockPointerType()) {
5810 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5811 ReplaceStmt(S, BlockCall);
5812 return BlockCall;
5813 }
5814 }
5815 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5816 RewriteCastExpr(CE);
5817 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005818 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5819 RewriteImplicitCastObjCExpr(ICE);
5820 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005821#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005822
Fariborz Jahanian11671902012-02-07 17:11:38 +00005823 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5824 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5825 ICE->getSubExpr(),
5826 SourceLocation());
5827 // Get the new text.
5828 std::string SStr;
5829 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005830 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005831 const std::string &Str = Buf.str();
5832
5833 printf("CAST = %s\n", &Str[0]);
5834 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5835 delete S;
5836 return Replacement;
5837 }
5838#endif
5839 // Return this stmt unmodified.
5840 return S;
5841}
5842
5843void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005844 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005845 if (isTopLevelBlockPointerType(FD->getType()))
5846 RewriteBlockPointerDecl(FD);
5847 if (FD->getType()->isObjCQualifiedIdType() ||
5848 FD->getType()->isObjCQualifiedInterfaceType())
5849 RewriteObjCQualifiedInterfaceTypes(FD);
5850 }
5851}
5852
5853/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5854/// main file of the input.
5855void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5856 switch (D->getKind()) {
5857 case Decl::Function: {
5858 FunctionDecl *FD = cast<FunctionDecl>(D);
5859 if (FD->isOverloadedOperator())
5860 return;
5861
5862 // Since function prototypes don't have ParmDecl's, we check the function
5863 // prototype. This enables us to rewrite function declarations and
5864 // definitions using the same code.
5865 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5866
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005867 if (!FD->isThisDeclarationADefinition())
5868 break;
5869
Fariborz Jahanian11671902012-02-07 17:11:38 +00005870 // FIXME: If this should support Obj-C++, support CXXTryStmt
5871 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5872 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005873 CurrentBody = Body;
5874 Body =
5875 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5876 FD->setBody(Body);
5877 CurrentBody = 0;
5878 if (PropParentMap) {
5879 delete PropParentMap;
5880 PropParentMap = 0;
5881 }
5882 // This synthesizes and inserts the block "impl" struct, invoke function,
5883 // and any copy/dispose helper functions.
5884 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005885 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005886 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005887 }
5888 break;
5889 }
5890 case Decl::ObjCMethod: {
5891 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5892 if (CompoundStmt *Body = MD->getCompoundBody()) {
5893 CurMethodDef = MD;
5894 CurrentBody = Body;
5895 Body =
5896 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5897 MD->setBody(Body);
5898 CurrentBody = 0;
5899 if (PropParentMap) {
5900 delete PropParentMap;
5901 PropParentMap = 0;
5902 }
5903 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005904 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005905 CurMethodDef = 0;
5906 }
5907 break;
5908 }
5909 case Decl::ObjCImplementation: {
5910 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5911 ClassImplementation.push_back(CI);
5912 break;
5913 }
5914 case Decl::ObjCCategoryImpl: {
5915 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5916 CategoryImplementation.push_back(CI);
5917 break;
5918 }
5919 case Decl::Var: {
5920 VarDecl *VD = cast<VarDecl>(D);
5921 RewriteObjCQualifiedInterfaceTypes(VD);
5922 if (isTopLevelBlockPointerType(VD->getType()))
5923 RewriteBlockPointerDecl(VD);
5924 else if (VD->getType()->isFunctionPointerType()) {
5925 CheckFunctionPointerDecl(VD->getType(), VD);
5926 if (VD->getInit()) {
5927 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5928 RewriteCastExpr(CE);
5929 }
5930 }
5931 } else if (VD->getType()->isRecordType()) {
5932 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5933 if (RD->isCompleteDefinition())
5934 RewriteRecordBody(RD);
5935 }
5936 if (VD->getInit()) {
5937 GlobalVarDecl = VD;
5938 CurrentBody = VD->getInit();
5939 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5940 CurrentBody = 0;
5941 if (PropParentMap) {
5942 delete PropParentMap;
5943 PropParentMap = 0;
5944 }
5945 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5946 GlobalVarDecl = 0;
5947
5948 // This is needed for blocks.
5949 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5950 RewriteCastExpr(CE);
5951 }
5952 }
5953 break;
5954 }
5955 case Decl::TypeAlias:
5956 case Decl::Typedef: {
5957 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5958 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5959 RewriteBlockPointerDecl(TD);
5960 else if (TD->getUnderlyingType()->isFunctionPointerType())
5961 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005962 else
5963 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005964 }
5965 break;
5966 }
5967 case Decl::CXXRecord:
5968 case Decl::Record: {
5969 RecordDecl *RD = cast<RecordDecl>(D);
5970 if (RD->isCompleteDefinition())
5971 RewriteRecordBody(RD);
5972 break;
5973 }
5974 default:
5975 break;
5976 }
5977 // Nothing yet.
5978}
5979
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005980/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5981/// protocol reference symbols in the for of:
5982/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5983static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5984 ObjCProtocolDecl *PDecl,
5985 std::string &Result) {
5986 // Also output .objc_protorefs$B section and its meta-data.
5987 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005988 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005989 Result += "struct _protocol_t *";
5990 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5991 Result += PDecl->getNameAsString();
5992 Result += " = &";
5993 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5994 Result += ";\n";
5995}
5996
Fariborz Jahanian11671902012-02-07 17:11:38 +00005997void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5998 if (Diags.hasErrorOccurred())
5999 return;
6000
6001 RewriteInclude();
6002
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006003 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006004 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006005 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006006 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006007 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6008 HandleTopLevelSingleDecl(FDecl);
6009 }
6010
Fariborz Jahanian11671902012-02-07 17:11:38 +00006011 // Here's a great place to add any extra declarations that may be needed.
6012 // Write out meta data for each @protocol(<expr>).
6013 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006014 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006015 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006016 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6017 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006018
6019 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006020
6021 if (ClassImplementation.size() || CategoryImplementation.size())
6022 RewriteImplementations();
6023
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006024 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6025 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6026 // Write struct declaration for the class matching its ivar declarations.
6027 // Note that for modern abi, this is postponed until the end of TU
6028 // because class extensions and the implementation might declare their own
6029 // private ivars.
6030 RewriteInterfaceDecl(CDecl);
6031 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006032
Fariborz Jahanian11671902012-02-07 17:11:38 +00006033 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6034 // we are done.
6035 if (const RewriteBuffer *RewriteBuf =
6036 Rewrite.getRewriteBufferFor(MainFileID)) {
6037 //printf("Changed:\n");
6038 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6039 } else {
6040 llvm::errs() << "No changes\n";
6041 }
6042
6043 if (ClassImplementation.size() || CategoryImplementation.size() ||
6044 ProtocolExprDecls.size()) {
6045 // Rewrite Objective-c meta data*
6046 std::string ResultStr;
6047 RewriteMetaDataIntoBuffer(ResultStr);
6048 // Emit metadata.
6049 *OutFile << ResultStr;
6050 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006051 // Emit ImageInfo;
6052 {
6053 std::string ResultStr;
6054 WriteImageInfo(ResultStr);
6055 *OutFile << ResultStr;
6056 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006057 OutFile->flush();
6058}
6059
6060void RewriteModernObjC::Initialize(ASTContext &context) {
6061 InitializeCommon(context);
6062
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006063 Preamble += "#ifndef __OBJC2__\n";
6064 Preamble += "#define __OBJC2__\n";
6065 Preamble += "#endif\n";
6066
Fariborz Jahanian11671902012-02-07 17:11:38 +00006067 // declaring objc_selector outside the parameter list removes a silly
6068 // scope related warning...
6069 if (IsHeader)
6070 Preamble = "#pragma once\n";
6071 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006072 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6073 Preamble += "\n\tstruct objc_object *superClass; ";
6074 // Add a constructor for creating temporary objects.
6075 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6076 Preamble += ": object(o), superClass(s) {} ";
6077 Preamble += "\n};\n";
6078
Fariborz Jahanian11671902012-02-07 17:11:38 +00006079 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006080 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006081 // These are currently generated.
6082 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006083 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006084 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006085 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6086 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006087 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006088 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006089 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6090 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006091 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006092
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006093 // These need be generated for performance. Currently they are not,
6094 // using API calls instead.
6095 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6096 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6097 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6098
Fariborz Jahanian11671902012-02-07 17:11:38 +00006099 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006100 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6101 Preamble += "typedef struct objc_object Protocol;\n";
6102 Preamble += "#define _REWRITER_typedef_Protocol\n";
6103 Preamble += "#endif\n";
6104 if (LangOpts.MicrosoftExt) {
6105 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6106 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006107 }
6108 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006109 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006110
6111 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6112 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6113 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6114 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6115 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6116
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006117 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006118 Preamble += "(const char *);\n";
6119 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6120 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006121 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006122 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006123 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006124 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006125 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6126 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006127 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006128 Preamble += "#ifdef _WIN64\n";
6129 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6130 Preamble += "#else\n";
6131 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6132 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006133 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6134 Preamble += "struct __objcFastEnumerationState {\n\t";
6135 Preamble += "unsigned long state;\n\t";
6136 Preamble += "void **itemsPtr;\n\t";
6137 Preamble += "unsigned long *mutationsPtr;\n\t";
6138 Preamble += "unsigned long extra[5];\n};\n";
6139 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6140 Preamble += "#define __FASTENUMERATIONSTATE\n";
6141 Preamble += "#endif\n";
6142 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6143 Preamble += "struct __NSConstantStringImpl {\n";
6144 Preamble += " int *isa;\n";
6145 Preamble += " int flags;\n";
6146 Preamble += " char *str;\n";
6147 Preamble += " long length;\n";
6148 Preamble += "};\n";
6149 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6150 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6151 Preamble += "#else\n";
6152 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6153 Preamble += "#endif\n";
6154 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6155 Preamble += "#endif\n";
6156 // Blocks preamble.
6157 Preamble += "#ifndef BLOCK_IMPL\n";
6158 Preamble += "#define BLOCK_IMPL\n";
6159 Preamble += "struct __block_impl {\n";
6160 Preamble += " void *isa;\n";
6161 Preamble += " int Flags;\n";
6162 Preamble += " int Reserved;\n";
6163 Preamble += " void *FuncPtr;\n";
6164 Preamble += "};\n";
6165 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6166 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6167 Preamble += "extern \"C\" __declspec(dllexport) "
6168 "void _Block_object_assign(void *, const void *, const int);\n";
6169 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6170 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6171 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6172 Preamble += "#else\n";
6173 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6174 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6175 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6176 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6177 Preamble += "#endif\n";
6178 Preamble += "#endif\n";
6179 if (LangOpts.MicrosoftExt) {
6180 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6181 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6182 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6183 Preamble += "#define __attribute__(X)\n";
6184 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006185 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006186 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006187 Preamble += "#endif\n";
6188 Preamble += "#ifndef __block\n";
6189 Preamble += "#define __block\n";
6190 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006191 }
6192 else {
6193 Preamble += "#define __block\n";
6194 Preamble += "#define __weak\n";
6195 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006196
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006197 // Declarations required for modern objective-c array and dictionary literals.
6198 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006199 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006200 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006201 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006202 Preamble += "\tva_list marker;\n";
6203 Preamble += "\tva_start(marker, count);\n";
6204 Preamble += "\tarr = new void *[count];\n";
6205 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6206 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6207 Preamble += "\tva_end( marker );\n";
6208 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006209 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006210 Preamble += "\tdelete[] arr;\n";
6211 Preamble += " }\n";
6212 Preamble += "};\n";
6213
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006214 // Declaration required for implementation of @autoreleasepool statement.
6215 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6216 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6217 Preamble += "struct __AtAutoreleasePool {\n";
6218 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6219 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6220 Preamble += " void * atautoreleasepoolobj;\n";
6221 Preamble += "};\n";
6222
Fariborz Jahanian11671902012-02-07 17:11:38 +00006223 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6224 // as this avoids warning in any 64bit/32bit compilation model.
6225 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6226}
6227
6228/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6229/// ivar offset.
6230void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6231 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006232 Result += "__OFFSETOFIVAR__(struct ";
6233 Result += ivar->getContainingInterface()->getNameAsString();
6234 if (LangOpts.MicrosoftExt)
6235 Result += "_IMPL";
6236 Result += ", ";
6237 if (ivar->isBitField())
6238 ObjCIvarBitfieldGroupDecl(ivar, Result);
6239 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006240 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006241 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006242}
6243
6244/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6245/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006246/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006247/// char *attributes;
6248/// }
6249
6250/// struct _prop_list_t {
6251/// uint32_t entsize; // sizeof(struct _prop_t)
6252/// uint32_t count_of_properties;
6253/// struct _prop_t prop_list[count_of_properties];
6254/// }
6255
6256/// struct _protocol_t;
6257
6258/// struct _protocol_list_t {
6259/// long protocol_count; // Note, this is 32/64 bit
6260/// struct _protocol_t * protocol_list[protocol_count];
6261/// }
6262
6263/// struct _objc_method {
6264/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006265/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006266/// char *_imp;
6267/// }
6268
6269/// struct _method_list_t {
6270/// uint32_t entsize; // sizeof(struct _objc_method)
6271/// uint32_t method_count;
6272/// struct _objc_method method_list[method_count];
6273/// }
6274
6275/// struct _protocol_t {
6276/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006277/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006278/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006279/// const struct method_list_t *instance_methods;
6280/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006281/// const struct method_list_t *optionalInstanceMethods;
6282/// const struct method_list_t *optionalClassMethods;
6283/// const struct _prop_list_t * properties;
6284/// const uint32_t size; // sizeof(struct _protocol_t)
6285/// const uint32_t flags; // = 0
6286/// const char ** extendedMethodTypes;
6287/// }
6288
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006289/// struct _ivar_t {
6290/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006291/// const char *name;
6292/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006293/// uint32_t alignment;
6294/// uint32_t size;
6295/// }
6296
6297/// struct _ivar_list_t {
6298/// uint32 entsize; // sizeof(struct _ivar_t)
6299/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006300/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006301/// }
6302
6303/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006304/// uint32_t flags;
6305/// uint32_t instanceStart;
6306/// uint32_t instanceSize;
6307/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006308/// const uint8_t *ivarLayout;
6309/// const char *name;
6310/// const struct _method_list_t *baseMethods;
6311/// const struct _protocol_list_t *baseProtocols;
6312/// const struct _ivar_list_t *ivars;
6313/// const uint8_t *weakIvarLayout;
6314/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006315/// }
6316
6317/// struct _class_t {
6318/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006319/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006320/// void *cache;
6321/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006322/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006323/// }
6324
6325/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006326/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006327/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006328/// const struct _method_list_t *instance_methods;
6329/// const struct _method_list_t *class_methods;
6330/// const struct _protocol_list_t *protocols;
6331/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006332/// }
6333
6334/// MessageRefTy - LLVM for:
6335/// struct _message_ref_t {
6336/// IMP messenger;
6337/// SEL name;
6338/// };
6339
6340/// SuperMessageRefTy - LLVM for:
6341/// struct _super_message_ref_t {
6342/// SUPER_IMP messenger;
6343/// SEL name;
6344/// };
6345
Fariborz Jahanian45489622012-03-14 18:09:23 +00006346static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006347 static bool meta_data_declared = false;
6348 if (meta_data_declared)
6349 return;
6350
6351 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006352 Result += "\tconst char *name;\n";
6353 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006354 Result += "};\n";
6355
6356 Result += "\nstruct _protocol_t;\n";
6357
Fariborz Jahanian11671902012-02-07 17:11:38 +00006358 Result += "\nstruct _objc_method {\n";
6359 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006360 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006361 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006362 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006363
6364 Result += "\nstruct _protocol_t {\n";
6365 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006366 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006367 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006368 Result += "\tconst struct method_list_t *instance_methods;\n";
6369 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006370 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6371 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6372 Result += "\tconst struct _prop_list_t * properties;\n";
6373 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6374 Result += "\tconst unsigned int flags; // = 0\n";
6375 Result += "\tconst char ** extendedMethodTypes;\n";
6376 Result += "};\n";
6377
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006378 Result += "\nstruct _ivar_t {\n";
6379 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006380 Result += "\tconst char *name;\n";
6381 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006382 Result += "\tunsigned int alignment;\n";
6383 Result += "\tunsigned int size;\n";
6384 Result += "};\n";
6385
6386 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006387 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006388 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006389 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006390 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6391 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006392 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006393 Result += "\tconst unsigned char *ivarLayout;\n";
6394 Result += "\tconst char *name;\n";
6395 Result += "\tconst struct _method_list_t *baseMethods;\n";
6396 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6397 Result += "\tconst struct _ivar_list_t *ivars;\n";
6398 Result += "\tconst unsigned char *weakIvarLayout;\n";
6399 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006400 Result += "};\n";
6401
6402 Result += "\nstruct _class_t {\n";
6403 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006404 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006405 Result += "\tvoid *cache;\n";
6406 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006407 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006408 Result += "};\n";
6409
6410 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006411 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006412 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006413 Result += "\tconst struct _method_list_t *instance_methods;\n";
6414 Result += "\tconst struct _method_list_t *class_methods;\n";
6415 Result += "\tconst struct _protocol_list_t *protocols;\n";
6416 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006417 Result += "};\n";
6418
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006419 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006420 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006421 meta_data_declared = true;
6422}
6423
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006424static void Write_protocol_list_t_TypeDecl(std::string &Result,
6425 long super_protocol_count) {
6426 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6427 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6428 Result += "\tstruct _protocol_t *super_protocols[";
6429 Result += utostr(super_protocol_count); Result += "];\n";
6430 Result += "}";
6431}
6432
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006433static void Write_method_list_t_TypeDecl(std::string &Result,
6434 unsigned int method_count) {
6435 Result += "struct /*_method_list_t*/"; Result += " {\n";
6436 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6437 Result += "\tunsigned int method_count;\n";
6438 Result += "\tstruct _objc_method method_list[";
6439 Result += utostr(method_count); Result += "];\n";
6440 Result += "}";
6441}
6442
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006443static void Write__prop_list_t_TypeDecl(std::string &Result,
6444 unsigned int property_count) {
6445 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6446 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6447 Result += "\tunsigned int count_of_properties;\n";
6448 Result += "\tstruct _prop_t prop_list[";
6449 Result += utostr(property_count); Result += "];\n";
6450 Result += "}";
6451}
6452
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006453static void Write__ivar_list_t_TypeDecl(std::string &Result,
6454 unsigned int ivar_count) {
6455 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6456 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6457 Result += "\tunsigned int count;\n";
6458 Result += "\tstruct _ivar_t ivar_list[";
6459 Result += utostr(ivar_count); Result += "];\n";
6460 Result += "}";
6461}
6462
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006463static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6464 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6465 StringRef VarName,
6466 StringRef ProtocolName) {
6467 if (SuperProtocols.size() > 0) {
6468 Result += "\nstatic ";
6469 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6470 Result += " "; Result += VarName;
6471 Result += ProtocolName;
6472 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6473 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6474 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6475 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6476 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6477 Result += SuperPD->getNameAsString();
6478 if (i == e-1)
6479 Result += "\n};\n";
6480 else
6481 Result += ",\n";
6482 }
6483 }
6484}
6485
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006486static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6487 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006488 ArrayRef<ObjCMethodDecl *> Methods,
6489 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006490 StringRef TopLevelDeclName,
6491 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006492 if (Methods.size() > 0) {
6493 Result += "\nstatic ";
6494 Write_method_list_t_TypeDecl(Result, Methods.size());
6495 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006496 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006497 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6498 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6499 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6500 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6501 ObjCMethodDecl *MD = Methods[i];
6502 if (i == 0)
6503 Result += "\t{{(struct objc_selector *)\"";
6504 else
6505 Result += "\t{(struct objc_selector *)\"";
6506 Result += (MD)->getSelector().getAsString(); Result += "\"";
6507 Result += ", ";
6508 std::string MethodTypeString;
6509 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6510 Result += "\""; Result += MethodTypeString; Result += "\"";
6511 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006512 if (!MethodImpl)
6513 Result += "0";
6514 else {
6515 Result += "(void *)";
6516 Result += RewriteObj.MethodInternalNames[MD];
6517 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006518 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006519 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006520 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006521 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006522 }
6523 Result += "};\n";
6524 }
6525}
6526
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006527static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006528 ASTContext *Context, std::string &Result,
6529 ArrayRef<ObjCPropertyDecl *> Properties,
6530 const Decl *Container,
6531 StringRef VarName,
6532 StringRef ProtocolName) {
6533 if (Properties.size() > 0) {
6534 Result += "\nstatic ";
6535 Write__prop_list_t_TypeDecl(Result, Properties.size());
6536 Result += " "; Result += VarName;
6537 Result += ProtocolName;
6538 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6539 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6540 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6541 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6542 ObjCPropertyDecl *PropDecl = Properties[i];
6543 if (i == 0)
6544 Result += "\t{{\"";
6545 else
6546 Result += "\t{\"";
6547 Result += PropDecl->getName(); Result += "\",";
6548 std::string PropertyTypeString, QuotePropertyTypeString;
6549 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6550 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6551 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6552 if (i == e-1)
6553 Result += "}}\n";
6554 else
6555 Result += "},\n";
6556 }
6557 Result += "};\n";
6558 }
6559}
6560
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006561// Metadata flags
6562enum MetaDataDlags {
6563 CLS = 0x0,
6564 CLS_META = 0x1,
6565 CLS_ROOT = 0x2,
6566 OBJC2_CLS_HIDDEN = 0x10,
6567 CLS_EXCEPTION = 0x20,
6568
6569 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6570 CLS_HAS_IVAR_RELEASER = 0x40,
6571 /// class was compiled with -fobjc-arr
6572 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6573};
6574
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006575static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6576 unsigned int flags,
6577 const std::string &InstanceStart,
6578 const std::string &InstanceSize,
6579 ArrayRef<ObjCMethodDecl *>baseMethods,
6580 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6581 ArrayRef<ObjCIvarDecl *>ivars,
6582 ArrayRef<ObjCPropertyDecl *>Properties,
6583 StringRef VarName,
6584 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006585 Result += "\nstatic struct _class_ro_t ";
6586 Result += VarName; Result += ClassName;
6587 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6588 Result += "\t";
6589 Result += llvm::utostr(flags); Result += ", ";
6590 Result += InstanceStart; Result += ", ";
6591 Result += InstanceSize; Result += ", \n";
6592 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006593 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6594 if (Triple.getArch() == llvm::Triple::x86_64)
6595 // uint32_t const reserved; // only when building for 64bit targets
6596 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006597 // const uint8_t * const ivarLayout;
6598 Result += "0, \n\t";
6599 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006600 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006601 if (baseMethods.size() > 0) {
6602 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006603 if (metaclass)
6604 Result += "_OBJC_$_CLASS_METHODS_";
6605 else
6606 Result += "_OBJC_$_INSTANCE_METHODS_";
6607 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006608 Result += ",\n\t";
6609 }
6610 else
6611 Result += "0, \n\t";
6612
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006613 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006614 Result += "(const struct _objc_protocol_list *)&";
6615 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6616 Result += ",\n\t";
6617 }
6618 else
6619 Result += "0, \n\t";
6620
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006621 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006622 Result += "(const struct _ivar_list_t *)&";
6623 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6624 Result += ",\n\t";
6625 }
6626 else
6627 Result += "0, \n\t";
6628
6629 // weakIvarLayout
6630 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006631 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006632 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006633 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006634 Result += ",\n";
6635 }
6636 else
6637 Result += "0, \n";
6638
6639 Result += "};\n";
6640}
6641
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006642static void Write_class_t(ASTContext *Context, std::string &Result,
6643 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006644 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6645 bool rootClass = (!CDecl->getSuperClass());
6646 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006647
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006648 if (!rootClass) {
6649 // Find the Root class
6650 RootClass = CDecl->getSuperClass();
6651 while (RootClass->getSuperClass()) {
6652 RootClass = RootClass->getSuperClass();
6653 }
6654 }
6655
6656 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006657 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006658 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006659 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006660 if (CDecl->getImplementation())
6661 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006662 else
6663 Result += "__declspec(dllimport) ";
6664
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006665 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006666 Result += CDecl->getNameAsString();
6667 Result += ";\n";
6668 }
6669 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006670 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006671 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006672 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006673 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006674 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006675 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006676 else
6677 Result += "__declspec(dllimport) ";
6678
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006679 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006680 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006681 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006682 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006683
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006684 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006685 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006686 if (RootClass->getImplementation())
6687 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006688 else
6689 Result += "__declspec(dllimport) ";
6690
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006691 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006692 Result += VarName;
6693 Result += RootClass->getNameAsString();
6694 Result += ";\n";
6695 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006696 }
6697
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006698 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6699 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006700 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6701 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006702 if (metaclass) {
6703 if (!rootClass) {
6704 Result += "0, // &"; Result += VarName;
6705 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006706 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006707 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006708 Result += CDecl->getSuperClass()->getNameAsString();
6709 Result += ",\n\t";
6710 }
6711 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006712 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006713 Result += CDecl->getNameAsString();
6714 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006715 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006716 Result += ",\n\t";
6717 }
6718 }
6719 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006720 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006721 Result += CDecl->getNameAsString();
6722 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006723 if (!rootClass) {
6724 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006725 Result += CDecl->getSuperClass()->getNameAsString();
6726 Result += ",\n\t";
6727 }
6728 else
6729 Result += "0,\n\t";
6730 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006731 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6732 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6733 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006734 Result += "&_OBJC_METACLASS_RO_$_";
6735 else
6736 Result += "&_OBJC_CLASS_RO_$_";
6737 Result += CDecl->getNameAsString();
6738 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006739
6740 // Add static function to initialize some of the meta-data fields.
6741 // avoid doing it twice.
6742 if (metaclass)
6743 return;
6744
6745 const ObjCInterfaceDecl *SuperClass =
6746 rootClass ? CDecl : CDecl->getSuperClass();
6747
6748 Result += "static void OBJC_CLASS_SETUP_$_";
6749 Result += CDecl->getNameAsString();
6750 Result += "(void ) {\n";
6751 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6752 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006753 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006754
6755 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006756 Result += ".superclass = ";
6757 if (rootClass)
6758 Result += "&OBJC_CLASS_$_";
6759 else
6760 Result += "&OBJC_METACLASS_$_";
6761
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006762 Result += SuperClass->getNameAsString(); Result += ";\n";
6763
6764 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6765 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6766
6767 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6768 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6769 Result += CDecl->getNameAsString(); Result += ";\n";
6770
6771 if (!rootClass) {
6772 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6773 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6774 Result += SuperClass->getNameAsString(); Result += ";\n";
6775 }
6776
6777 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6778 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6779 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006780}
6781
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006782static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6783 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006784 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006785 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006786 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6787 ArrayRef<ObjCMethodDecl *> ClassMethods,
6788 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6789 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006790 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006791 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006792 // must declare an extern class object in case this class is not implemented
6793 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006794 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006795 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006796 if (ClassDecl->getImplementation())
6797 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006798 else
6799 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006800
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006801 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006802 Result += "OBJC_CLASS_$_"; Result += ClassName;
6803 Result += ";\n";
6804
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006805 Result += "\nstatic struct _category_t ";
6806 Result += "_OBJC_$_CATEGORY_";
6807 Result += ClassName; Result += "_$_"; Result += CatName;
6808 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6809 Result += "{\n";
6810 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006811 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006812 Result += ",\n";
6813 if (InstanceMethods.size() > 0) {
6814 Result += "\t(const struct _method_list_t *)&";
6815 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6816 Result += ClassName; Result += "_$_"; Result += CatName;
6817 Result += ",\n";
6818 }
6819 else
6820 Result += "\t0,\n";
6821
6822 if (ClassMethods.size() > 0) {
6823 Result += "\t(const struct _method_list_t *)&";
6824 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6825 Result += ClassName; Result += "_$_"; Result += CatName;
6826 Result += ",\n";
6827 }
6828 else
6829 Result += "\t0,\n";
6830
6831 if (RefedProtocols.size() > 0) {
6832 Result += "\t(const struct _protocol_list_t *)&";
6833 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6834 Result += ClassName; Result += "_$_"; Result += CatName;
6835 Result += ",\n";
6836 }
6837 else
6838 Result += "\t0,\n";
6839
6840 if (ClassProperties.size() > 0) {
6841 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6842 Result += ClassName; Result += "_$_"; Result += CatName;
6843 Result += ",\n";
6844 }
6845 else
6846 Result += "\t0,\n";
6847
6848 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006849
6850 // Add static function to initialize the class pointer in the category structure.
6851 Result += "static void OBJC_CATEGORY_SETUP_$_";
6852 Result += ClassDecl->getNameAsString();
6853 Result += "_$_";
6854 Result += CatName;
6855 Result += "(void ) {\n";
6856 Result += "\t_OBJC_$_CATEGORY_";
6857 Result += ClassDecl->getNameAsString();
6858 Result += "_$_";
6859 Result += CatName;
6860 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6861 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006862}
6863
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006864static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6865 ASTContext *Context, std::string &Result,
6866 ArrayRef<ObjCMethodDecl *> Methods,
6867 StringRef VarName,
6868 StringRef ProtocolName) {
6869 if (Methods.size() == 0)
6870 return;
6871
6872 Result += "\nstatic const char *";
6873 Result += VarName; Result += ProtocolName;
6874 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6875 Result += "{\n";
6876 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6877 ObjCMethodDecl *MD = Methods[i];
6878 std::string MethodTypeString, QuoteMethodTypeString;
6879 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6880 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6881 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6882 if (i == e-1)
6883 Result += "\n};\n";
6884 else {
6885 Result += ",\n";
6886 }
6887 }
6888}
6889
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006890static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6891 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006892 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006893 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006894 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006895 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6896 // this is what happens:
6897 /**
6898 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6899 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6900 Class->getVisibility() == HiddenVisibility)
6901 Visibility shoud be: HiddenVisibility;
6902 else
6903 Visibility shoud be: DefaultVisibility;
6904 */
6905
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006906 Result += "\n";
6907 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6908 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006909 if (Context->getLangOpts().MicrosoftExt)
6910 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6911
6912 if (!Context->getLangOpts().MicrosoftExt ||
6913 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006914 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006915 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006916 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006917 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006918 if (Ivars[i]->isBitField())
6919 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6920 else
6921 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006922 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6923 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006924 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6925 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006926 if (Ivars[i]->isBitField()) {
6927 // skip over rest of the ivar bitfields.
6928 SKIP_BITFIELDS(i , e, Ivars);
6929 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006930 }
6931}
6932
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006933static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6934 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006935 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006936 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006937 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006938 if (OriginalIvars.size() > 0) {
6939 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6940 SmallVector<ObjCIvarDecl *, 8> Ivars;
6941 // strip off all but the first ivar bitfield from each group of ivars.
6942 // Such ivars in the ivar list table will be replaced by their grouping struct
6943 // 'ivar'.
6944 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6945 if (OriginalIvars[i]->isBitField()) {
6946 Ivars.push_back(OriginalIvars[i]);
6947 // skip over rest of the ivar bitfields.
6948 SKIP_BITFIELDS(i , e, OriginalIvars);
6949 }
6950 else
6951 Ivars.push_back(OriginalIvars[i]);
6952 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006953
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006954 Result += "\nstatic ";
6955 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6956 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006957 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006958 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6959 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6960 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6961 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6962 ObjCIvarDecl *IvarDecl = Ivars[i];
6963 if (i == 0)
6964 Result += "\t{{";
6965 else
6966 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006967 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006968 if (Ivars[i]->isBitField())
6969 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6970 else
6971 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006972 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006973
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006974 Result += "\"";
6975 if (Ivars[i]->isBitField())
6976 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6977 else
6978 Result += IvarDecl->getName();
6979 Result += "\", ";
6980
6981 QualType IVQT = IvarDecl->getType();
6982 if (IvarDecl->isBitField())
6983 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6984
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006985 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006986 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006987 IvarDecl);
6988 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6989 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6990
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006991 // FIXME. this alignment represents the host alignment and need be changed to
6992 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006993 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006994 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006995 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006996 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006997 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006998 if (i == e-1)
6999 Result += "}}\n";
7000 else
7001 Result += "},\n";
7002 }
7003 Result += "};\n";
7004 }
7005}
7006
Fariborz Jahanian11671902012-02-07 17:11:38 +00007007/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007008void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7009 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007010
Fariborz Jahanian11671902012-02-07 17:11:38 +00007011 // Do not synthesize the protocol more than once.
7012 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7013 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007014 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007015
7016 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7017 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007018 // Must write out all protocol definitions in current qualifier list,
7019 // and in their nested qualifiers before writing out current definition.
7020 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7021 E = PDecl->protocol_end(); I != E; ++I)
7022 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007023
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007024 // Construct method lists.
7025 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7026 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7027 for (ObjCProtocolDecl::instmeth_iterator
7028 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7029 I != E; ++I) {
7030 ObjCMethodDecl *MD = *I;
7031 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7032 OptInstanceMethods.push_back(MD);
7033 } else {
7034 InstanceMethods.push_back(MD);
7035 }
7036 }
7037
7038 for (ObjCProtocolDecl::classmeth_iterator
7039 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7040 I != E; ++I) {
7041 ObjCMethodDecl *MD = *I;
7042 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7043 OptClassMethods.push_back(MD);
7044 } else {
7045 ClassMethods.push_back(MD);
7046 }
7047 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007048 std::vector<ObjCMethodDecl *> AllMethods;
7049 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7050 AllMethods.push_back(InstanceMethods[i]);
7051 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7052 AllMethods.push_back(ClassMethods[i]);
7053 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7054 AllMethods.push_back(OptInstanceMethods[i]);
7055 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7056 AllMethods.push_back(OptClassMethods[i]);
7057
7058 Write__extendedMethodTypes_initializer(*this, Context, Result,
7059 AllMethods,
7060 "_OBJC_PROTOCOL_METHOD_TYPES_",
7061 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007062 // Protocol's super protocol list
7063 std::vector<ObjCProtocolDecl *> SuperProtocols;
7064 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7065 E = PDecl->protocol_end(); I != E; ++I)
7066 SuperProtocols.push_back(*I);
7067
7068 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7069 "_OBJC_PROTOCOL_REFS_",
7070 PDecl->getNameAsString());
7071
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007072 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007073 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007074 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007075
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007076 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007077 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007078 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007079
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007080 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007081 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007082 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007083
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007084 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007085 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007086 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007087
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007088 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007089 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007090 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007091 /* Container */0,
7092 "_OBJC_PROTOCOL_PROPERTIES_",
7093 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007094
Fariborz Jahanian48985802012-02-08 00:50:52 +00007095 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007096 Result += "\n";
7097 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007098 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007099 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007100 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007101 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7102 Result += "\t0,\n"; // id is; is null
7103 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007104 if (SuperProtocols.size() > 0) {
7105 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7106 Result += PDecl->getNameAsString(); Result += ",\n";
7107 }
7108 else
7109 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007110 if (InstanceMethods.size() > 0) {
7111 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7112 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007113 }
7114 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007115 Result += "\t0,\n";
7116
7117 if (ClassMethods.size() > 0) {
7118 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7119 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007120 }
7121 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007122 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007123
Fariborz Jahanian48985802012-02-08 00:50:52 +00007124 if (OptInstanceMethods.size() > 0) {
7125 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7126 Result += PDecl->getNameAsString(); Result += ",\n";
7127 }
7128 else
7129 Result += "\t0,\n";
7130
7131 if (OptClassMethods.size() > 0) {
7132 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7133 Result += PDecl->getNameAsString(); Result += ",\n";
7134 }
7135 else
7136 Result += "\t0,\n";
7137
7138 if (ProtocolProperties.size() > 0) {
7139 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7140 Result += PDecl->getNameAsString(); Result += ",\n";
7141 }
7142 else
7143 Result += "\t0,\n";
7144
7145 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7146 Result += "\t0,\n";
7147
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007148 if (AllMethods.size() > 0) {
7149 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7150 Result += PDecl->getNameAsString();
7151 Result += "\n};\n";
7152 }
7153 else
7154 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007155
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007156 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007157 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007158 Result += "struct _protocol_t *";
7159 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7160 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7161 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007162
Fariborz Jahanian11671902012-02-07 17:11:38 +00007163 // Mark this protocol as having been generated.
7164 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7165 llvm_unreachable("protocol already synthesized");
7166
7167}
7168
7169void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7170 const ObjCList<ObjCProtocolDecl> &Protocols,
7171 StringRef prefix, StringRef ClassName,
7172 std::string &Result) {
7173 if (Protocols.empty()) return;
7174
7175 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007176 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007177
7178 // Output the top lovel protocol meta-data for the class.
7179 /* struct _objc_protocol_list {
7180 struct _objc_protocol_list *next;
7181 int protocol_count;
7182 struct _objc_protocol *class_protocols[];
7183 }
7184 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007185 Result += "\n";
7186 if (LangOpts.MicrosoftExt)
7187 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7188 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007189 Result += "\tstruct _objc_protocol_list *next;\n";
7190 Result += "\tint protocol_count;\n";
7191 Result += "\tstruct _objc_protocol *class_protocols[";
7192 Result += utostr(Protocols.size());
7193 Result += "];\n} _OBJC_";
7194 Result += prefix;
7195 Result += "_PROTOCOLS_";
7196 Result += ClassName;
7197 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7198 "{\n\t0, ";
7199 Result += utostr(Protocols.size());
7200 Result += "\n";
7201
7202 Result += "\t,{&_OBJC_PROTOCOL_";
7203 Result += Protocols[0]->getNameAsString();
7204 Result += " \n";
7205
7206 for (unsigned i = 1; i != Protocols.size(); i++) {
7207 Result += "\t ,&_OBJC_PROTOCOL_";
7208 Result += Protocols[i]->getNameAsString();
7209 Result += "\n";
7210 }
7211 Result += "\t }\n};\n";
7212}
7213
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007214/// hasObjCExceptionAttribute - Return true if this class or any super
7215/// class has the __objc_exception__ attribute.
7216/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7217static bool hasObjCExceptionAttribute(ASTContext &Context,
7218 const ObjCInterfaceDecl *OID) {
7219 if (OID->hasAttr<ObjCExceptionAttr>())
7220 return true;
7221 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7222 return hasObjCExceptionAttribute(Context, Super);
7223 return false;
7224}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007225
Fariborz Jahanian11671902012-02-07 17:11:38 +00007226void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7227 std::string &Result) {
7228 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7229
7230 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007231 if (CDecl->isImplicitInterfaceDecl())
7232 assert(false &&
7233 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007234
Fariborz Jahanian45489622012-03-14 18:09:23 +00007235 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007236 SmallVector<ObjCIvarDecl *, 8> IVars;
7237
7238 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7239 IVD; IVD = IVD->getNextIvar()) {
7240 // Ignore unnamed bit-fields.
7241 if (!IVD->getDeclName())
7242 continue;
7243 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007244 }
7245
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007246 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007247 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007248 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007249
7250 // Build _objc_method_list for class's instance methods if needed
7251 SmallVector<ObjCMethodDecl *, 32>
7252 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7253
7254 // If any of our property implementations have associated getters or
7255 // setters, produce metadata for them as well.
7256 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7257 PropEnd = IDecl->propimpl_end();
7258 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007259 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007260 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007261 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007262 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007263 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007264 if (!PD)
7265 continue;
7266 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007267 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007268 InstanceMethods.push_back(Getter);
7269 if (PD->isReadOnly())
7270 continue;
7271 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007272 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007273 InstanceMethods.push_back(Setter);
7274 }
7275
7276 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7277 "_OBJC_$_INSTANCE_METHODS_",
7278 IDecl->getNameAsString(), true);
7279
7280 SmallVector<ObjCMethodDecl *, 32>
7281 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7282
7283 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7284 "_OBJC_$_CLASS_METHODS_",
7285 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007286
7287 // Protocols referenced in class declaration?
7288 // Protocol's super protocol list
7289 std::vector<ObjCProtocolDecl *> RefedProtocols;
7290 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7291 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7292 E = Protocols.end();
7293 I != E; ++I) {
7294 RefedProtocols.push_back(*I);
7295 // Must write out all protocol definitions in current qualifier list,
7296 // and in their nested qualifiers before writing out current definition.
7297 RewriteObjCProtocolMetaData(*I, Result);
7298 }
7299
7300 Write_protocol_list_initializer(Context, Result,
7301 RefedProtocols,
7302 "_OBJC_CLASS_PROTOCOLS_$_",
7303 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007304
7305 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007306 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007307 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007308 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007309 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007310 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007311
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007312
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007313 // Data for initializing _class_ro_t metaclass meta-data
7314 uint32_t flags = CLS_META;
7315 std::string InstanceSize;
7316 std::string InstanceStart;
7317
7318
7319 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7320 if (classIsHidden)
7321 flags |= OBJC2_CLS_HIDDEN;
7322
7323 if (!CDecl->getSuperClass())
7324 // class is root
7325 flags |= CLS_ROOT;
7326 InstanceSize = "sizeof(struct _class_t)";
7327 InstanceStart = InstanceSize;
7328 Write__class_ro_t_initializer(Context, Result, flags,
7329 InstanceStart, InstanceSize,
7330 ClassMethods,
7331 0,
7332 0,
7333 0,
7334 "_OBJC_METACLASS_RO_$_",
7335 CDecl->getNameAsString());
7336
7337
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007338 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007339 flags = CLS;
7340 if (classIsHidden)
7341 flags |= OBJC2_CLS_HIDDEN;
7342
7343 if (hasObjCExceptionAttribute(*Context, CDecl))
7344 flags |= CLS_EXCEPTION;
7345
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007346 if (!CDecl->getSuperClass())
7347 // class is root
7348 flags |= CLS_ROOT;
7349
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007350 InstanceSize.clear();
7351 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007352 if (!ObjCSynthesizedStructs.count(CDecl)) {
7353 InstanceSize = "0";
7354 InstanceStart = "0";
7355 }
7356 else {
7357 InstanceSize = "sizeof(struct ";
7358 InstanceSize += CDecl->getNameAsString();
7359 InstanceSize += "_IMPL)";
7360
7361 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7362 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007363 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007364 }
7365 else
7366 InstanceStart = InstanceSize;
7367 }
7368 Write__class_ro_t_initializer(Context, Result, flags,
7369 InstanceStart, InstanceSize,
7370 InstanceMethods,
7371 RefedProtocols,
7372 IVars,
7373 ClassProperties,
7374 "_OBJC_CLASS_RO_$_",
7375 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007376
7377 Write_class_t(Context, Result,
7378 "OBJC_METACLASS_$_",
7379 CDecl, /*metaclass*/true);
7380
7381 Write_class_t(Context, Result,
7382 "OBJC_CLASS_$_",
7383 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007384
7385 if (ImplementationIsNonLazy(IDecl))
7386 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007387
Fariborz Jahanian11671902012-02-07 17:11:38 +00007388}
7389
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007390void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7391 int ClsDefCount = ClassImplementation.size();
7392 if (!ClsDefCount)
7393 return;
7394 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7395 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7396 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7397 for (int i = 0; i < ClsDefCount; i++) {
7398 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7399 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7400 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7401 Result += CDecl->getName(); Result += ",\n";
7402 }
7403 Result += "};\n";
7404}
7405
Fariborz Jahanian11671902012-02-07 17:11:38 +00007406void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7407 int ClsDefCount = ClassImplementation.size();
7408 int CatDefCount = CategoryImplementation.size();
7409
7410 // For each implemented class, write out all its meta data.
7411 for (int i = 0; i < ClsDefCount; i++)
7412 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7413
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007414 RewriteClassSetupInitHook(Result);
7415
Fariborz Jahanian11671902012-02-07 17:11:38 +00007416 // For each implemented category, write out all its meta data.
7417 for (int i = 0; i < CatDefCount; i++)
7418 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7419
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007420 RewriteCategorySetupInitHook(Result);
7421
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007422 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007423 if (LangOpts.MicrosoftExt)
7424 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007425 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7426 Result += llvm::utostr(ClsDefCount); Result += "]";
7427 Result +=
7428 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7429 "regular,no_dead_strip\")))= {\n";
7430 for (int i = 0; i < ClsDefCount; i++) {
7431 Result += "\t&OBJC_CLASS_$_";
7432 Result += ClassImplementation[i]->getNameAsString();
7433 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007434 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007435 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007436
7437 if (!DefinedNonLazyClasses.empty()) {
7438 if (LangOpts.MicrosoftExt)
7439 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7440 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7441 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7442 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7443 Result += ",\n";
7444 }
7445 Result += "};\n";
7446 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007447 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007448
7449 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007450 if (LangOpts.MicrosoftExt)
7451 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007452 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7453 Result += llvm::utostr(CatDefCount); Result += "]";
7454 Result +=
7455 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7456 "regular,no_dead_strip\")))= {\n";
7457 for (int i = 0; i < CatDefCount; i++) {
7458 Result += "\t&_OBJC_$_CATEGORY_";
7459 Result +=
7460 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7461 Result += "_$_";
7462 Result += CategoryImplementation[i]->getNameAsString();
7463 Result += ",\n";
7464 }
7465 Result += "};\n";
7466 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007467
7468 if (!DefinedNonLazyCategories.empty()) {
7469 if (LangOpts.MicrosoftExt)
7470 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7471 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7472 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7473 Result += "\t&_OBJC_$_CATEGORY_";
7474 Result +=
7475 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7476 Result += "_$_";
7477 Result += DefinedNonLazyCategories[i]->getNameAsString();
7478 Result += ",\n";
7479 }
7480 Result += "};\n";
7481 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007482}
7483
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007484void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7485 if (LangOpts.MicrosoftExt)
7486 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7487
7488 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7489 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007490 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007491}
7492
Fariborz Jahanian11671902012-02-07 17:11:38 +00007493/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7494/// implementation.
7495void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7496 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007497 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007498 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7499 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007500 ObjCCategoryDecl *CDecl
7501 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007502
7503 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007504 FullCategoryName += "_$_";
7505 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007506
7507 // Build _objc_method_list for class's instance methods if needed
7508 SmallVector<ObjCMethodDecl *, 32>
7509 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7510
7511 // If any of our property implementations have associated getters or
7512 // setters, produce metadata for them as well.
7513 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7514 PropEnd = IDecl->propimpl_end();
7515 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007516 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007517 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007518 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007519 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007520 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007521 if (!PD)
7522 continue;
7523 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7524 InstanceMethods.push_back(Getter);
7525 if (PD->isReadOnly())
7526 continue;
7527 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7528 InstanceMethods.push_back(Setter);
7529 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007530
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007531 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7532 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7533 FullCategoryName, true);
7534
7535 SmallVector<ObjCMethodDecl *, 32>
7536 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7537
7538 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7539 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7540 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007541
7542 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007543 // Protocol's super protocol list
7544 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007545 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7546 E = CDecl->protocol_end();
7547
7548 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007549 RefedProtocols.push_back(*I);
7550 // Must write out all protocol definitions in current qualifier list,
7551 // and in their nested qualifiers before writing out current definition.
7552 RewriteObjCProtocolMetaData(*I, Result);
7553 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007554
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007555 Write_protocol_list_initializer(Context, Result,
7556 RefedProtocols,
7557 "_OBJC_CATEGORY_PROTOCOLS_$_",
7558 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007559
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007560 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007561 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007562 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007563 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007564 "_OBJC_$_PROP_LIST_",
7565 FullCategoryName);
7566
7567 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007568 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007569 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007570 InstanceMethods,
7571 ClassMethods,
7572 RefedProtocols,
7573 ClassProperties);
7574
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007575 // Determine if this category is also "non-lazy".
7576 if (ImplementationIsNonLazy(IDecl))
7577 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007578
7579}
7580
7581void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7582 int CatDefCount = CategoryImplementation.size();
7583 if (!CatDefCount)
7584 return;
7585 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7586 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7587 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7588 for (int i = 0; i < CatDefCount; i++) {
7589 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7590 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7591 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7592 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7593 Result += ClassDecl->getName();
7594 Result += "_$_";
7595 Result += CatDecl->getName();
7596 Result += ",\n";
7597 }
7598 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007599}
7600
7601// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7602/// class methods.
7603template<typename MethodIterator>
7604void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7605 MethodIterator MethodEnd,
7606 bool IsInstanceMethod,
7607 StringRef prefix,
7608 StringRef ClassName,
7609 std::string &Result) {
7610 if (MethodBegin == MethodEnd) return;
7611
7612 if (!objc_impl_method) {
7613 /* struct _objc_method {
7614 SEL _cmd;
7615 char *method_types;
7616 void *_imp;
7617 }
7618 */
7619 Result += "\nstruct _objc_method {\n";
7620 Result += "\tSEL _cmd;\n";
7621 Result += "\tchar *method_types;\n";
7622 Result += "\tvoid *_imp;\n";
7623 Result += "};\n";
7624
7625 objc_impl_method = true;
7626 }
7627
7628 // Build _objc_method_list for class's methods if needed
7629
7630 /* struct {
7631 struct _objc_method_list *next_method;
7632 int method_count;
7633 struct _objc_method method_list[];
7634 }
7635 */
7636 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007637 Result += "\n";
7638 if (LangOpts.MicrosoftExt) {
7639 if (IsInstanceMethod)
7640 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7641 else
7642 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7643 }
7644 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007645 Result += "\tstruct _objc_method_list *next_method;\n";
7646 Result += "\tint method_count;\n";
7647 Result += "\tstruct _objc_method method_list[";
7648 Result += utostr(NumMethods);
7649 Result += "];\n} _OBJC_";
7650 Result += prefix;
7651 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7652 Result += "_METHODS_";
7653 Result += ClassName;
7654 Result += " __attribute__ ((used, section (\"__OBJC, __";
7655 Result += IsInstanceMethod ? "inst" : "cls";
7656 Result += "_meth\")))= ";
7657 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7658
7659 Result += "\t,{{(SEL)\"";
7660 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7661 std::string MethodTypeString;
7662 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7663 Result += "\", \"";
7664 Result += MethodTypeString;
7665 Result += "\", (void *)";
7666 Result += MethodInternalNames[*MethodBegin];
7667 Result += "}\n";
7668 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7669 Result += "\t ,{(SEL)\"";
7670 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7671 std::string MethodTypeString;
7672 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7673 Result += "\", \"";
7674 Result += MethodTypeString;
7675 Result += "\", (void *)";
7676 Result += MethodInternalNames[*MethodBegin];
7677 Result += "}\n";
7678 }
7679 Result += "\t }\n};\n";
7680}
7681
7682Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7683 SourceRange OldRange = IV->getSourceRange();
7684 Expr *BaseExpr = IV->getBase();
7685
7686 // Rewrite the base, but without actually doing replaces.
7687 {
7688 DisableReplaceStmtScope S(*this);
7689 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7690 IV->setBase(BaseExpr);
7691 }
7692
7693 ObjCIvarDecl *D = IV->getDecl();
7694
7695 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007696
Fariborz Jahanian11671902012-02-07 17:11:38 +00007697 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7698 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007699 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007700 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7701 // lookup which class implements the instance variable.
7702 ObjCInterfaceDecl *clsDeclared = 0;
7703 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7704 clsDeclared);
7705 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7706
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007707 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007708 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007709 if (D->isBitField())
7710 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7711 else
7712 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007713
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007714 ReferencedIvars[clsDeclared].insert(D);
7715
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007716 // cast offset to "char *".
7717 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7718 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007719 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007720 BaseExpr);
7721 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7722 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007723 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007724 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7725 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007726 SourceLocation());
7727 BinaryOperator *addExpr =
7728 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7729 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007730 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007731 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007732 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7733 SourceLocation(),
7734 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007735 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007736 if (D->isBitField())
7737 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007738
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007739 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007740 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007741 RD = RD->getDefinition();
7742 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007743 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007744 ObjCContainerDecl *CDecl =
7745 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7746 // ivar in class extensions requires special treatment.
7747 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7748 CDecl = CatDecl->getClassInterface();
7749 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007750 RecName += "_IMPL";
7751 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7752 SourceLocation(), SourceLocation(),
7753 &Context->Idents.get(RecName.c_str()));
7754 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7755 unsigned UnsignedIntSize =
7756 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7757 Expr *Zero = IntegerLiteral::Create(*Context,
7758 llvm::APInt(UnsignedIntSize, 0),
7759 Context->UnsignedIntTy, SourceLocation());
7760 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7761 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7762 Zero);
7763 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7764 SourceLocation(),
7765 &Context->Idents.get(D->getNameAsString()),
7766 IvarT, 0,
7767 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007768 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007769 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7770 FD->getType(), VK_LValue,
7771 OK_Ordinary);
7772 IvarT = Context->getDecltypeType(ME, ME->getType());
7773 }
7774 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007775 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007776 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007777
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007778 castExpr = NoTypeInfoCStyleCastExpr(Context,
7779 castT,
7780 CK_BitCast,
7781 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007782
7783
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007784 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007785 VK_LValue, OK_Ordinary,
7786 SourceLocation());
7787 PE = new (Context) ParenExpr(OldRange.getBegin(),
7788 OldRange.getEnd(),
7789 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007790
7791 if (D->isBitField()) {
7792 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7793 SourceLocation(),
7794 &Context->Idents.get(D->getNameAsString()),
7795 D->getType(), 0,
7796 /*BitWidth=*/D->getBitWidth(),
7797 /*Mutable=*/true,
7798 ICIS_NoInit);
7799 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7800 FD->getType(), VK_LValue,
7801 OK_Ordinary);
7802 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007803
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007804 }
7805 else
7806 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007807 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007808
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007809 ReplaceStmtWithRange(IV, Replacement, OldRange);
7810 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007811}