blob: 34ffd227237b34b3c6a3bcd5b6b2790b4184cc5a [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-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 };
61 static const int OBJC_ABI_VERSION = 7;
62
63 Rewriter Rewrite;
64 DiagnosticsEngine &Diags;
65 const LangOptions &LangOpts;
66 ASTContext *Context;
67 SourceManager *SM;
68 TranslationUnitDecl *TUDecl;
69 FileID MainFileID;
70 const char *MainFileStart, *MainFileEnd;
71 Stmt *CurrentBody;
72 ParentMap *PropParentMap; // created lazily.
73 std::string InFileName;
74 raw_ostream* OutFile;
75 std::string Preamble;
76
77 TypeDecl *ProtocolTypeDecl;
78 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000079 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000080 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000081 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000082 // ObjC string constant support.
83 unsigned NumObjCStringLiterals;
84 VarDecl *ConstantStringClassReference;
85 RecordDecl *NSStringRecord;
86
87 // ObjC foreach break/continue generation support.
88 int BcLabelCount;
89
90 unsigned TryFinallyContainsReturnDiag;
91 // Needed for super.
92 ObjCMethodDecl *CurMethodDef;
93 RecordDecl *SuperStructDecl;
94 RecordDecl *ConstantStringDecl;
95
96 FunctionDecl *MsgSendFunctionDecl;
97 FunctionDecl *MsgSendSuperFunctionDecl;
98 FunctionDecl *MsgSendStretFunctionDecl;
99 FunctionDecl *MsgSendSuperStretFunctionDecl;
100 FunctionDecl *MsgSendFpretFunctionDecl;
101 FunctionDecl *GetClassFunctionDecl;
102 FunctionDecl *GetMetaClassFunctionDecl;
103 FunctionDecl *GetSuperClassFunctionDecl;
104 FunctionDecl *SelGetUidFunctionDecl;
105 FunctionDecl *CFStringFunctionDecl;
106 FunctionDecl *SuperContructorFunctionDecl;
107 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000108
109 /* Misc. containers needed for meta-data rewrite. */
110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000115 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000116 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000117 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
118 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
119
120 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000121 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000122
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000123 SmallVector<Stmt *, 32> Stmts;
124 SmallVector<int, 8> ObjCBcLabelNo;
125 // Remember all the @protocol(<expr>) expressions.
126 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
127
128 llvm::DenseSet<uint64_t> CopyDestroyCache;
129
130 // Block expressions.
131 SmallVector<BlockExpr *, 32> Blocks;
132 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
John McCallf4b88a42012-03-10 09:33:50 +0000135 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000136
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000138 // Block related declarations.
139 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141 SmallVector<ValueDecl *, 8> BlockByRefDecls;
142 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146
147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000148 llvm::DenseMap<ObjCInterfaceDecl *,
149 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
150
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000151 // ivar bitfield grouping containers
152 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154 // This container maps an <class, group number for ivar> tuple to the type
155 // of the struct where the bitfield belongs.
156 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000157 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000158
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000159 // This maps an original source AST to it's rewritten form. This allows
160 // us to avoid rewriting the same node twice (which is very uncommon).
161 // This is needed to support some of the exotic property rewriting.
162 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164 // Needed for header files being rewritten
165 bool IsHeader;
166 bool SilenceRewriteMacroWarning;
Fariborz Jahanianada71912013-02-08 00:27:34 +0000167 bool GenerateLineInfo;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000168 bool objc_impl_method;
169
170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
174
175 public:
176 DisableReplaceStmtScope(RewriteModernObjC &R)
177 : R(R), SavedValue(R.DisableReplaceStmt) {
178 R.DisableReplaceStmt = true;
179 }
180 ~DisableReplaceStmtScope() {
181 R.DisableReplaceStmt = SavedValue;
182 }
183 };
184 void InitializeCommon(ASTContext &context);
185
186 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000187 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000188 // Top Level Driver code.
189 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
190 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
191 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
192 if (!Class->isThisDeclarationADefinition()) {
193 RewriteForwardClassDecl(D);
194 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000195 } else {
196 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000197 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000198 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000199 }
200 }
201
202 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
203 if (!Proto->isThisDeclarationADefinition()) {
204 RewriteForwardProtocolDecl(D);
205 break;
206 }
207 }
208
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000209 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
210 // Under modern abi, we cannot translate body of the function
211 // yet until all class extensions and its implementation is seen.
212 // This is because they may introduce new bitfields which must go
213 // into their grouping struct.
214 if (FDecl->isThisDeclarationADefinition() &&
215 // Not c functions defined inside an objc container.
216 !FDecl->isTopLevelDeclInObjCContainer()) {
217 FunctionDefinitionsSeen.push_back(FDecl);
218 break;
219 }
220 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000221 HandleTopLevelSingleDecl(*I);
222 }
223 return true;
224 }
225 void HandleTopLevelSingleDecl(Decl *D);
226 void HandleDeclInMainFile(Decl *D);
227 RewriteModernObjC(std::string inFile, raw_ostream *OS,
228 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000229 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000230
231 ~RewriteModernObjC() {}
232
233 virtual void HandleTranslationUnit(ASTContext &C);
234
235 void ReplaceStmt(Stmt *Old, Stmt *New) {
236 Stmt *ReplacingStmt = ReplacedNodes[Old];
237
238 if (ReplacingStmt)
239 return; // We can't rewrite the same node twice.
240
241 if (DisableReplaceStmt)
242 return;
243
244 // If replacement succeeded or warning disabled return with no warning.
245 if (!Rewrite.ReplaceStmt(Old, New)) {
246 ReplacedNodes[Old] = New;
247 return;
248 }
249 if (SilenceRewriteMacroWarning)
250 return;
251 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
252 << Old->getSourceRange();
253 }
254
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
256 if (DisableReplaceStmt)
257 return;
258
259 // Measure the old text.
260 int Size = Rewrite.getRangeSize(SrcRange);
261 if (Size == -1) {
262 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
263 << Old->getSourceRange();
264 return;
265 }
266 // Get the new text.
267 std::string SStr;
268 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000269 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000270 const std::string &Str = S.str();
271
272 // If replacement succeeded or warning disabled return with no warning.
273 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
274 ReplacedNodes[Old] = New;
275 return;
276 }
277 if (SilenceRewriteMacroWarning)
278 return;
279 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
280 << Old->getSourceRange();
281 }
282
283 void InsertText(SourceLocation Loc, StringRef Str,
284 bool InsertAfter = true) {
285 // If insertion succeeded or warning disabled return with no warning.
286 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
287 SilenceRewriteMacroWarning)
288 return;
289
290 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
291 }
292
293 void ReplaceText(SourceLocation Start, unsigned OrigLength,
294 StringRef Str) {
295 // If removal succeeded or warning disabled return with no warning.
296 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
297 SilenceRewriteMacroWarning)
298 return;
299
300 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
301 }
302
303 // Syntactic Rewriting.
304 void RewriteRecordBody(RecordDecl *RD);
305 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000306 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000307 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
308 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000309 void RewriteForwardClassDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000310 void RewriteForwardClassDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000311 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
312 const std::string &typedefString);
313 void RewriteImplementations();
314 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
315 ObjCImplementationDecl *IMD,
316 ObjCCategoryImplDecl *CID);
317 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
318 void RewriteImplementationDecl(Decl *Dcl);
319 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
320 ObjCMethodDecl *MDecl, std::string &ResultStr);
321 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
322 const FunctionType *&FPRetType);
323 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
324 ValueDecl *VD, bool def=false);
325 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
326 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
327 void RewriteForwardProtocolDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000328 void RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000329 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
330 void RewriteProperty(ObjCPropertyDecl *prop);
331 void RewriteFunctionDecl(FunctionDecl *FD);
332 void RewriteBlockPointerType(std::string& Str, QualType Type);
333 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000334 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000335 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
336 void RewriteTypeOfDecl(VarDecl *VD);
337 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000338
339 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000340
341 // Expression Rewriting.
342 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
343 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
344 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
345 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
346 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
347 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
348 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000349 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000350 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000351 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000352 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000353 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000354 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000355 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000356 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
357 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
358 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
359 SourceLocation OrigEnd);
360 Stmt *RewriteBreakStmt(BreakStmt *S);
361 Stmt *RewriteContinueStmt(ContinueStmt *S);
362 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000363 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000364 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000366 // Computes ivar bitfield group no.
367 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
368 // Names field decl. for ivar bitfield group.
369 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
370 // Names struct type for ivar bitfield group.
371 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
372 // Names symbol for ivar bitfield group field offset.
373 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
374 // Given an ivar bitfield, it builds (or finds) its group record type.
375 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
376 QualType SynthesizeBitfieldGroupStructType(
377 ObjCIvarDecl *IV,
378 SmallVectorImpl<ObjCIvarDecl *> &IVars);
379
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000380 // Block rewriting.
381 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
382
383 // Block specific rewrite rules.
384 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000385 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000386 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000387 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
388 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
389
390 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
391 std::string &Result);
392
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000393 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000394 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000395 bool &IsNamedDefinition);
396 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
397 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000398
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000399 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
400
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000401 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
402 std::string &Result);
403
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000404 virtual void Initialize(ASTContext &context);
405
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000406 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000407 // rewriting routines on the new ASTs.
408 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
409 Expr **args, unsigned nargs,
410 SourceLocation StartLoc=SourceLocation(),
411 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000412
413 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
414 QualType msgSendType,
415 QualType returnType,
416 SmallVectorImpl<QualType> &ArgTypes,
417 SmallVectorImpl<Expr*> &MsgExprs,
418 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419
420 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
421 SourceLocation StartLoc=SourceLocation(),
422 SourceLocation EndLoc=SourceLocation());
423
424 void SynthCountByEnumWithState(std::string &buf);
425 void SynthMsgSendFunctionDecl();
426 void SynthMsgSendSuperFunctionDecl();
427 void SynthMsgSendStretFunctionDecl();
428 void SynthMsgSendFpretFunctionDecl();
429 void SynthMsgSendSuperStretFunctionDecl();
430 void SynthGetClassFunctionDecl();
431 void SynthGetMetaClassFunctionDecl();
432 void SynthGetSuperClassFunctionDecl();
433 void SynthSelGetUidFunctionDecl();
434 void SynthSuperContructorFunctionDecl();
435
436 // Rewriting metadata
437 template<typename MethodIterator>
438 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
439 MethodIterator MethodEnd,
440 bool IsInstanceMethod,
441 StringRef prefix,
442 StringRef ClassName,
443 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000444 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
445 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000446 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000447 const ObjCList<ObjCProtocolDecl> &Prots,
448 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000449 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000450 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000451 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000452
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000453 void RewriteMetaDataIntoBuffer(std::string &Result);
454 void WriteImageInfo(std::string &Result);
455 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000456 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000457 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000458
459 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000460 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000462 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000463
464
465 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469 StringRef funcName, std::string Tag);
470 std::string SynthesizeBlockImpl(BlockExpr *CE,
471 std::string Tag, std::string Desc);
472 std::string SynthesizeBlockDescriptor(std::string DescTag,
473 std::string ImplTag,
474 int i, StringRef funcName,
475 unsigned hasCopy);
476 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478 StringRef FunName);
479 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000481 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000482
483 // Misc. helper routines.
484 QualType getProtocolType();
485 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000486 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491 void CollectBlockDeclRefInfo(BlockExpr *Exp);
492 void GetBlockDeclRefExprs(Stmt *S);
493 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000494 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000495 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
496
497 // We avoid calling Type::isBlockPointerType(), since it operates on the
498 // canonical type. We only care if the top-level type is a closure pointer.
499 bool isTopLevelBlockPointerType(QualType T) {
500 return isa<BlockPointerType>(T);
501 }
502
503 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504 /// to a function pointer type and upon success, returns true; false
505 /// otherwise.
506 bool convertBlockPointerToFunctionPointer(QualType &T) {
507 if (isTopLevelBlockPointerType(T)) {
508 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
509 T = Context->getPointerType(BPT->getPointeeType());
510 return true;
511 }
512 return false;
513 }
514
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000515 bool convertObjCTypeToCStyleType(QualType &T);
516
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000517 bool needToScanForQualifiers(QualType T);
518 QualType getSuperStructType();
519 QualType getConstantStringStructType();
520 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
522
523 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000524 if (T->isObjCQualifiedIdType()) {
525 bool isConst = T.isConstQualified();
526 T = isConst ? Context->getObjCIdType().withConst()
527 : Context->getObjCIdType();
528 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000529 else if (T->isObjCQualifiedClassType())
530 T = Context->getObjCClassType();
531 else if (T->isObjCObjectPointerType() &&
532 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
533 if (const ObjCObjectPointerType * OBJPT =
534 T->getAsObjCInterfacePointerType()) {
535 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
536 T = QualType(IFaceT, 0);
537 T = Context->getPointerType(T);
538 }
539 }
540 }
541
542 // FIXME: This predicate seems like it would be useful to add to ASTContext.
543 bool isObjCType(QualType T) {
544 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
545 return false;
546
547 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
548
549 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
550 OCT == Context->getCanonicalType(Context->getObjCClassType()))
551 return true;
552
553 if (const PointerType *PT = OCT->getAs<PointerType>()) {
554 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
555 PT->getPointeeType()->isObjCQualifiedIdType())
556 return true;
557 }
558 return false;
559 }
560 bool PointerTypeTakesAnyBlockArguments(QualType QT);
561 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562 void GetExtentOfArgList(const char *Name, const char *&LParen,
563 const char *&RParen);
564
565 void QuoteDoublequotes(std::string &From, std::string &To) {
566 for (unsigned i = 0; i < From.length(); i++) {
567 if (From[i] == '"')
568 To += "\\\"";
569 else
570 To += From[i];
571 }
572 }
573
574 QualType getSimpleFunctionType(QualType result,
575 const QualType *args,
576 unsigned numArgs,
577 bool variadic = false) {
578 if (result == Context->getObjCInstanceType())
579 result = Context->getObjCIdType();
580 FunctionProtoType::ExtProtoInfo fpi;
581 fpi.Variadic = variadic;
582 return Context->getFunctionType(result, args, numArgs, fpi);
583 }
584
585 // Helper function: create a CStyleCastExpr with trivial type source info.
586 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
587 CastKind Kind, Expr *E) {
588 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
589 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
590 SourceLocation(), SourceLocation());
591 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000592
593 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
594 IdentifierInfo* II = &Context->Idents.get("load");
595 Selector LoadSel = Context->Selectors.getSelector(0, &II);
596 return OD->getClassMethod(LoadSel) != 0;
597 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000598 };
599
600}
601
602void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
603 NamedDecl *D) {
604 if (const FunctionProtoType *fproto
605 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
606 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
607 E = fproto->arg_type_end(); I && (I != E); ++I)
608 if (isTopLevelBlockPointerType(*I)) {
609 // All the args are checked/rewritten. Don't call twice!
610 RewriteBlockPointerDecl(D);
611 break;
612 }
613 }
614}
615
616void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
617 const PointerType *PT = funcType->getAs<PointerType>();
618 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
619 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
620}
621
622static bool IsHeaderFile(const std::string &Filename) {
623 std::string::size_type DotPos = Filename.rfind('.');
624
625 if (DotPos == std::string::npos) {
626 // no file extension
627 return false;
628 }
629
630 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
631 // C header: .h
632 // C++ header: .hh or .H;
633 return Ext == "h" || Ext == "hh" || Ext == "H";
634}
635
636RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
637 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000638 bool silenceMacroWarn,
639 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000640 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000641 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000642 IsHeader = IsHeaderFile(inFile);
643 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
644 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000645 // FIXME. This should be an error. But if block is not called, it is OK. And it
646 // may break including some headers.
647 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
648 "rewriting block literal declared in global scope is not implemented");
649
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000650 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
651 DiagnosticsEngine::Warning,
652 "rewriter doesn't support user-specified control flow semantics "
653 "for @try/@finally (code may not execute properly)");
654}
655
656ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
657 raw_ostream* OS,
658 DiagnosticsEngine &Diags,
659 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000660 bool SilenceRewriteMacroWarning,
661 bool LineInfo) {
662 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
663 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000664}
665
666void RewriteModernObjC::InitializeCommon(ASTContext &context) {
667 Context = &context;
668 SM = &Context->getSourceManager();
669 TUDecl = Context->getTranslationUnitDecl();
670 MsgSendFunctionDecl = 0;
671 MsgSendSuperFunctionDecl = 0;
672 MsgSendStretFunctionDecl = 0;
673 MsgSendSuperStretFunctionDecl = 0;
674 MsgSendFpretFunctionDecl = 0;
675 GetClassFunctionDecl = 0;
676 GetMetaClassFunctionDecl = 0;
677 GetSuperClassFunctionDecl = 0;
678 SelGetUidFunctionDecl = 0;
679 CFStringFunctionDecl = 0;
680 ConstantStringClassReference = 0;
681 NSStringRecord = 0;
682 CurMethodDef = 0;
683 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000684 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000685 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000686 SuperStructDecl = 0;
687 ProtocolTypeDecl = 0;
688 ConstantStringDecl = 0;
689 BcLabelCount = 0;
690 SuperContructorFunctionDecl = 0;
691 NumObjCStringLiterals = 0;
692 PropParentMap = 0;
693 CurrentBody = 0;
694 DisableReplaceStmt = false;
695 objc_impl_method = false;
696
697 // Get the ID and start/end of the main file.
698 MainFileID = SM->getMainFileID();
699 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
700 MainFileStart = MainBuf->getBufferStart();
701 MainFileEnd = MainBuf->getBufferEnd();
702
David Blaikie4e4d0842012-03-11 07:00:24 +0000703 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000704}
705
706//===----------------------------------------------------------------------===//
707// Top Level Driver Code
708//===----------------------------------------------------------------------===//
709
710void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
711 if (Diags.hasErrorOccurred())
712 return;
713
714 // Two cases: either the decl could be in the main file, or it could be in a
715 // #included file. If the former, rewrite it now. If the later, check to see
716 // if we rewrote the #include/#import.
717 SourceLocation Loc = D->getLocation();
718 Loc = SM->getExpansionLoc(Loc);
719
720 // If this is for a builtin, ignore it.
721 if (Loc.isInvalid()) return;
722
723 // Look for built-in declarations that we need to refer during the rewrite.
724 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
725 RewriteFunctionDecl(FD);
726 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
727 // declared in <Foundation/NSString.h>
728 if (FVD->getName() == "_NSConstantStringClassReference") {
729 ConstantStringClassReference = FVD;
730 return;
731 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000732 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
733 RewriteCategoryDecl(CD);
734 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
735 if (PD->isThisDeclarationADefinition())
736 RewriteProtocolDecl(PD);
737 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000738 // FIXME. This will not work in all situations and leaving it out
739 // is harmless.
740 // RewriteLinkageSpec(LSD);
741
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000742 // Recurse into linkage specifications
743 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
744 DIEnd = LSD->decls_end();
745 DI != DIEnd; ) {
746 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
747 if (!IFace->isThisDeclarationADefinition()) {
748 SmallVector<Decl *, 8> DG;
749 SourceLocation StartLoc = IFace->getLocStart();
750 do {
751 if (isa<ObjCInterfaceDecl>(*DI) &&
752 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
753 StartLoc == (*DI)->getLocStart())
754 DG.push_back(*DI);
755 else
756 break;
757
758 ++DI;
759 } while (DI != DIEnd);
760 RewriteForwardClassDecl(DG);
761 continue;
762 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000763 else {
764 // Keep track of all interface declarations seen.
765 ObjCInterfacesSeen.push_back(IFace);
766 ++DI;
767 continue;
768 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000769 }
770
771 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
772 if (!Proto->isThisDeclarationADefinition()) {
773 SmallVector<Decl *, 8> DG;
774 SourceLocation StartLoc = Proto->getLocStart();
775 do {
776 if (isa<ObjCProtocolDecl>(*DI) &&
777 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
778 StartLoc == (*DI)->getLocStart())
779 DG.push_back(*DI);
780 else
781 break;
782
783 ++DI;
784 } while (DI != DIEnd);
785 RewriteForwardProtocolDecl(DG);
786 continue;
787 }
788 }
789
790 HandleTopLevelSingleDecl(*DI);
791 ++DI;
792 }
793 }
794 // If we have a decl in the main file, see if we should rewrite it.
795 if (SM->isFromMainFile(Loc))
796 return HandleDeclInMainFile(D);
797}
798
799//===----------------------------------------------------------------------===//
800// Syntactic (non-AST) Rewriting Code
801//===----------------------------------------------------------------------===//
802
803void RewriteModernObjC::RewriteInclude() {
804 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
805 StringRef MainBuf = SM->getBufferData(MainFileID);
806 const char *MainBufStart = MainBuf.begin();
807 const char *MainBufEnd = MainBuf.end();
808 size_t ImportLen = strlen("import");
809
810 // Loop over the whole file, looking for includes.
811 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
812 if (*BufPtr == '#') {
813 if (++BufPtr == MainBufEnd)
814 return;
815 while (*BufPtr == ' ' || *BufPtr == '\t')
816 if (++BufPtr == MainBufEnd)
817 return;
818 if (!strncmp(BufPtr, "import", ImportLen)) {
819 // replace import with include
820 SourceLocation ImportLoc =
821 LocStart.getLocWithOffset(BufPtr-MainBufStart);
822 ReplaceText(ImportLoc, ImportLen, "include");
823 BufPtr += ImportLen;
824 }
825 }
826 }
827}
828
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000829static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
830 ObjCIvarDecl *IvarDecl, std::string &Result) {
831 Result += "OBJC_IVAR_$_";
832 Result += IDecl->getName();
833 Result += "$";
834 Result += IvarDecl->getName();
835}
836
837std::string
838RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
839 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
840
841 // Build name of symbol holding ivar offset.
842 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000843 if (D->isBitField())
844 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
845 else
846 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000847
848
849 std::string S = "(*(";
850 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000851 if (D->isBitField())
852 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000853
854 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
855 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
856 RD = RD->getDefinition();
857 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858 // decltype(((Foo_IMPL*)0)->bar) *
859 ObjCContainerDecl *CDecl =
860 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
861 // ivar in class extensions requires special treatment.
862 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
863 CDecl = CatDecl->getClassInterface();
864 std::string RecName = CDecl->getName();
865 RecName += "_IMPL";
866 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
867 SourceLocation(), SourceLocation(),
868 &Context->Idents.get(RecName.c_str()));
869 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
870 unsigned UnsignedIntSize =
871 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
872 Expr *Zero = IntegerLiteral::Create(*Context,
873 llvm::APInt(UnsignedIntSize, 0),
874 Context->UnsignedIntTy, SourceLocation());
875 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
876 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
877 Zero);
878 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
879 SourceLocation(),
880 &Context->Idents.get(D->getNameAsString()),
881 IvarT, 0,
882 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000883 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000884 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
885 FD->getType(), VK_LValue,
886 OK_Ordinary);
887 IvarT = Context->getDecltypeType(ME, ME->getType());
888 }
889 }
890 convertObjCTypeToCStyleType(IvarT);
891 QualType castT = Context->getPointerType(IvarT);
892 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
893 S += TypeString;
894 S += ")";
895
896 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
897 S += "((char *)self + ";
898 S += IvarOffsetName;
899 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000900 if (D->isBitField()) {
901 S += ".";
902 S += D->getNameAsString();
903 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000904 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000905 return S;
906}
907
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000908/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
909/// been found in the class implementation. In this case, it must be synthesized.
910static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
911 ObjCPropertyDecl *PD,
912 bool getter) {
913 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
914 : !IMP->getInstanceMethod(PD->getSetterName());
915
916}
917
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000918void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
919 ObjCImplementationDecl *IMD,
920 ObjCCategoryImplDecl *CID) {
921 static bool objcGetPropertyDefined = false;
922 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000923 SourceLocation startGetterSetterLoc;
924
925 if (PID->getLocStart().isValid()) {
926 SourceLocation startLoc = PID->getLocStart();
927 InsertText(startLoc, "// ");
928 const char *startBuf = SM->getCharacterData(startLoc);
929 assert((*startBuf == '@') && "bogus @synthesize location");
930 const char *semiBuf = strchr(startBuf, ';');
931 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
932 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
933 }
934 else
935 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000936
937 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
938 return; // FIXME: is this correct?
939
940 // Generate the 'getter' function.
941 ObjCPropertyDecl *PD = PID->getPropertyDecl();
942 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
943
944 if (!OID)
945 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000946 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000947 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000948 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
949 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000950 ObjCPropertyDecl::OBJC_PR_copy));
951 std::string Getr;
952 if (GenGetProperty && !objcGetPropertyDefined) {
953 objcGetPropertyDefined = true;
954 // FIXME. Is this attribute correct in all cases?
955 Getr = "\nextern \"C\" __declspec(dllimport) "
956 "id objc_getProperty(id, SEL, long, bool);\n";
957 }
958 RewriteObjCMethodDecl(OID->getContainingInterface(),
959 PD->getGetterMethodDecl(), Getr);
960 Getr += "{ ";
961 // Synthesize an explicit cast to gain access to the ivar.
962 // See objc-act.c:objc_synthesize_new_getter() for details.
963 if (GenGetProperty) {
964 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
965 Getr += "typedef ";
966 const FunctionType *FPRetType = 0;
967 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
968 FPRetType);
969 Getr += " _TYPE";
970 if (FPRetType) {
971 Getr += ")"; // close the precedence "scope" for "*".
972
973 // Now, emit the argument types (if any).
974 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
975 Getr += "(";
976 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
977 if (i) Getr += ", ";
978 std::string ParamStr = FT->getArgType(i).getAsString(
979 Context->getPrintingPolicy());
980 Getr += ParamStr;
981 }
982 if (FT->isVariadic()) {
983 if (FT->getNumArgs()) Getr += ", ";
984 Getr += "...";
985 }
986 Getr += ")";
987 } else
988 Getr += "()";
989 }
990 Getr += ";\n";
991 Getr += "return (_TYPE)";
992 Getr += "objc_getProperty(self, _cmd, ";
993 RewriteIvarOffsetComputation(OID, Getr);
994 Getr += ", 1)";
995 }
996 else
997 Getr += "return " + getIvarAccessString(OID);
998 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000999 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001000 }
1001
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001002 if (PD->isReadOnly() ||
1003 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001004 return;
1005
1006 // Generate the 'setter' function.
1007 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001008 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001009 ObjCPropertyDecl::OBJC_PR_copy);
1010 if (GenSetProperty && !objcSetPropertyDefined) {
1011 objcSetPropertyDefined = true;
1012 // FIXME. Is this attribute correct in all cases?
1013 Setr = "\nextern \"C\" __declspec(dllimport) "
1014 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1015 }
1016
1017 RewriteObjCMethodDecl(OID->getContainingInterface(),
1018 PD->getSetterMethodDecl(), Setr);
1019 Setr += "{ ";
1020 // Synthesize an explicit cast to initialize the ivar.
1021 // See objc-act.c:objc_synthesize_new_setter() for details.
1022 if (GenSetProperty) {
1023 Setr += "objc_setProperty (self, _cmd, ";
1024 RewriteIvarOffsetComputation(OID, Setr);
1025 Setr += ", (id)";
1026 Setr += PD->getName();
1027 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001028 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001029 Setr += "0, ";
1030 else
1031 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001032 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001033 Setr += "1)";
1034 else
1035 Setr += "0)";
1036 }
1037 else {
1038 Setr += getIvarAccessString(OID) + " = ";
1039 Setr += PD->getName();
1040 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001041 Setr += "; }\n";
1042 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001043}
1044
1045static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1046 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001047 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001048 typedefString += ForwardDecl->getNameAsString();
1049 typedefString += "\n";
1050 typedefString += "#define _REWRITER_typedef_";
1051 typedefString += ForwardDecl->getNameAsString();
1052 typedefString += "\n";
1053 typedefString += "typedef struct objc_object ";
1054 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001055 // typedef struct { } _objc_exc_Classname;
1056 typedefString += ";\ntypedef struct {} _objc_exc_";
1057 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001058 typedefString += ";\n#endif\n";
1059}
1060
1061void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1062 const std::string &typedefString) {
1063 SourceLocation startLoc = ClassDecl->getLocStart();
1064 const char *startBuf = SM->getCharacterData(startLoc);
1065 const char *semiPtr = strchr(startBuf, ';');
1066 // Replace the @class with typedefs corresponding to the classes.
1067 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1068}
1069
1070void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1071 std::string typedefString;
1072 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1073 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1074 if (I == D.begin()) {
1075 // Translate to typedef's that forward reference structs with the same name
1076 // as the class. As a convenience, we include the original declaration
1077 // as a comment.
1078 typedefString += "// @class ";
1079 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001080 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001081 }
1082 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1083 }
1084 DeclGroupRef::iterator I = D.begin();
1085 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1086}
1087
1088void RewriteModernObjC::RewriteForwardClassDecl(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001089 const SmallVector<Decl *, 8> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001090 std::string typedefString;
1091 for (unsigned i = 0; i < D.size(); i++) {
1092 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1093 if (i == 0) {
1094 typedefString += "// @class ";
1095 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001096 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001097 }
1098 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1099 }
1100 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1101}
1102
1103void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1104 // When method is a synthesized one, such as a getter/setter there is
1105 // nothing to rewrite.
1106 if (Method->isImplicit())
1107 return;
1108 SourceLocation LocStart = Method->getLocStart();
1109 SourceLocation LocEnd = Method->getLocEnd();
1110
1111 if (SM->getExpansionLineNumber(LocEnd) >
1112 SM->getExpansionLineNumber(LocStart)) {
1113 InsertText(LocStart, "#if 0\n");
1114 ReplaceText(LocEnd, 1, ";\n#endif\n");
1115 } else {
1116 InsertText(LocStart, "// ");
1117 }
1118}
1119
1120void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1121 SourceLocation Loc = prop->getAtLoc();
1122
1123 ReplaceText(Loc, 0, "// ");
1124 // FIXME: handle properties that are declared across multiple lines.
1125}
1126
1127void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1128 SourceLocation LocStart = CatDecl->getLocStart();
1129
1130 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001131 if (CatDecl->getIvarRBraceLoc().isValid()) {
1132 ReplaceText(LocStart, 1, "/** ");
1133 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1134 }
1135 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001136 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001137 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001138
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001139 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1140 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001141 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001142
1143 for (ObjCCategoryDecl::instmeth_iterator
1144 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1145 I != E; ++I)
1146 RewriteMethodDeclaration(*I);
1147 for (ObjCCategoryDecl::classmeth_iterator
1148 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1149 I != E; ++I)
1150 RewriteMethodDeclaration(*I);
1151
1152 // Lastly, comment out the @end.
1153 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1154 strlen("@end"), "/* @end */");
1155}
1156
1157void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1158 SourceLocation LocStart = PDecl->getLocStart();
1159 assert(PDecl->isThisDeclarationADefinition());
1160
1161 // FIXME: handle protocol headers that are declared across multiple lines.
1162 ReplaceText(LocStart, 0, "// ");
1163
1164 for (ObjCProtocolDecl::instmeth_iterator
1165 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1166 I != E; ++I)
1167 RewriteMethodDeclaration(*I);
1168 for (ObjCProtocolDecl::classmeth_iterator
1169 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1170 I != E; ++I)
1171 RewriteMethodDeclaration(*I);
1172
1173 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1174 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001175 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001176
1177 // Lastly, comment out the @end.
1178 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1179 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1180
1181 // Must comment out @optional/@required
1182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
1184 for (const char *p = startBuf; p < endBuf; p++) {
1185 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1186 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1187 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1188
1189 }
1190 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1191 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1192 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1193
1194 }
1195 }
1196}
1197
1198void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1199 SourceLocation LocStart = (*D.begin())->getLocStart();
1200 if (LocStart.isInvalid())
1201 llvm_unreachable("Invalid SourceLocation");
1202 // FIXME: handle forward protocol that are declared across multiple lines.
1203 ReplaceText(LocStart, 0, "// ");
1204}
1205
1206void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001207RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001208 SourceLocation LocStart = DG[0]->getLocStart();
1209 if (LocStart.isInvalid())
1210 llvm_unreachable("Invalid SourceLocation");
1211 // FIXME: handle forward protocol that are declared across multiple lines.
1212 ReplaceText(LocStart, 0, "// ");
1213}
1214
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001215void
1216RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1217 SourceLocation LocStart = LSD->getExternLoc();
1218 if (LocStart.isInvalid())
1219 llvm_unreachable("Invalid extern SourceLocation");
1220
1221 ReplaceText(LocStart, 0, "// ");
1222 if (!LSD->hasBraces())
1223 return;
1224 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1225 SourceLocation LocRBrace = LSD->getRBraceLoc();
1226 if (LocRBrace.isInvalid())
1227 llvm_unreachable("Invalid rbrace SourceLocation");
1228 ReplaceText(LocRBrace, 0, "// ");
1229}
1230
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001231void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1232 const FunctionType *&FPRetType) {
1233 if (T->isObjCQualifiedIdType())
1234 ResultStr += "id";
1235 else if (T->isFunctionPointerType() ||
1236 T->isBlockPointerType()) {
1237 // needs special handling, since pointer-to-functions have special
1238 // syntax (where a decaration models use).
1239 QualType retType = T;
1240 QualType PointeeTy;
1241 if (const PointerType* PT = retType->getAs<PointerType>())
1242 PointeeTy = PT->getPointeeType();
1243 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1244 PointeeTy = BPT->getPointeeType();
1245 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1246 ResultStr += FPRetType->getResultType().getAsString(
1247 Context->getPrintingPolicy());
1248 ResultStr += "(*";
1249 }
1250 } else
1251 ResultStr += T.getAsString(Context->getPrintingPolicy());
1252}
1253
1254void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1255 ObjCMethodDecl *OMD,
1256 std::string &ResultStr) {
1257 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1258 const FunctionType *FPRetType = 0;
1259 ResultStr += "\nstatic ";
1260 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1261 ResultStr += " ";
1262
1263 // Unique method name
1264 std::string NameStr;
1265
1266 if (OMD->isInstanceMethod())
1267 NameStr += "_I_";
1268 else
1269 NameStr += "_C_";
1270
1271 NameStr += IDecl->getNameAsString();
1272 NameStr += "_";
1273
1274 if (ObjCCategoryImplDecl *CID =
1275 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1276 NameStr += CID->getNameAsString();
1277 NameStr += "_";
1278 }
1279 // Append selector names, replacing ':' with '_'
1280 {
1281 std::string selString = OMD->getSelector().getAsString();
1282 int len = selString.size();
1283 for (int i = 0; i < len; i++)
1284 if (selString[i] == ':')
1285 selString[i] = '_';
1286 NameStr += selString;
1287 }
1288 // Remember this name for metadata emission
1289 MethodInternalNames[OMD] = NameStr;
1290 ResultStr += NameStr;
1291
1292 // Rewrite arguments
1293 ResultStr += "(";
1294
1295 // invisible arguments
1296 if (OMD->isInstanceMethod()) {
1297 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1298 selfTy = Context->getPointerType(selfTy);
1299 if (!LangOpts.MicrosoftExt) {
1300 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1301 ResultStr += "struct ";
1302 }
1303 // When rewriting for Microsoft, explicitly omit the structure name.
1304 ResultStr += IDecl->getNameAsString();
1305 ResultStr += " *";
1306 }
1307 else
1308 ResultStr += Context->getObjCClassType().getAsString(
1309 Context->getPrintingPolicy());
1310
1311 ResultStr += " self, ";
1312 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1313 ResultStr += " _cmd";
1314
1315 // Method arguments.
1316 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1317 E = OMD->param_end(); PI != E; ++PI) {
1318 ParmVarDecl *PDecl = *PI;
1319 ResultStr += ", ";
1320 if (PDecl->getType()->isObjCQualifiedIdType()) {
1321 ResultStr += "id ";
1322 ResultStr += PDecl->getNameAsString();
1323 } else {
1324 std::string Name = PDecl->getNameAsString();
1325 QualType QT = PDecl->getType();
1326 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001327 (void)convertBlockPointerToFunctionPointer(QT);
1328 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001329 ResultStr += Name;
1330 }
1331 }
1332 if (OMD->isVariadic())
1333 ResultStr += ", ...";
1334 ResultStr += ") ";
1335
1336 if (FPRetType) {
1337 ResultStr += ")"; // close the precedence "scope" for "*".
1338
1339 // Now, emit the argument types (if any).
1340 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1341 ResultStr += "(";
1342 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1343 if (i) ResultStr += ", ";
1344 std::string ParamStr = FT->getArgType(i).getAsString(
1345 Context->getPrintingPolicy());
1346 ResultStr += ParamStr;
1347 }
1348 if (FT->isVariadic()) {
1349 if (FT->getNumArgs()) ResultStr += ", ";
1350 ResultStr += "...";
1351 }
1352 ResultStr += ")";
1353 } else {
1354 ResultStr += "()";
1355 }
1356 }
1357}
1358void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1359 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1360 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1361
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001362 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001363 if (IMD->getIvarRBraceLoc().isValid()) {
1364 ReplaceText(IMD->getLocStart(), 1, "/** ");
1365 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001366 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001367 else {
1368 InsertText(IMD->getLocStart(), "// ");
1369 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001370 }
1371 else
1372 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001373
1374 for (ObjCCategoryImplDecl::instmeth_iterator
1375 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1376 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1377 I != E; ++I) {
1378 std::string ResultStr;
1379 ObjCMethodDecl *OMD = *I;
1380 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1381 SourceLocation LocStart = OMD->getLocStart();
1382 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1383
1384 const char *startBuf = SM->getCharacterData(LocStart);
1385 const char *endBuf = SM->getCharacterData(LocEnd);
1386 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1387 }
1388
1389 for (ObjCCategoryImplDecl::classmeth_iterator
1390 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1391 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1392 I != E; ++I) {
1393 std::string ResultStr;
1394 ObjCMethodDecl *OMD = *I;
1395 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1396 SourceLocation LocStart = OMD->getLocStart();
1397 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1398
1399 const char *startBuf = SM->getCharacterData(LocStart);
1400 const char *endBuf = SM->getCharacterData(LocEnd);
1401 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1402 }
1403 for (ObjCCategoryImplDecl::propimpl_iterator
1404 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1405 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1406 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001407 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001408 }
1409
1410 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1411}
1412
1413void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001414 // Do not synthesize more than once.
1415 if (ObjCSynthesizedStructs.count(ClassDecl))
1416 return;
1417 // Make sure super class's are written before current class is written.
1418 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1419 while (SuperClass) {
1420 RewriteInterfaceDecl(SuperClass);
1421 SuperClass = SuperClass->getSuperClass();
1422 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001423 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001424 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001425 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001426 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001427 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1428
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001429 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001430 // Mark this typedef as having been written into its c++ equivalent.
1431 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001432
1433 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001434 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001435 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001436 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001437 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001438 I != E; ++I)
1439 RewriteMethodDeclaration(*I);
1440 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001441 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001442 I != E; ++I)
1443 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001444
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001445 // Lastly, comment out the @end.
1446 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1447 "/* @end */");
1448 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001449}
1450
1451Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1452 SourceRange OldRange = PseudoOp->getSourceRange();
1453
1454 // We just magically know some things about the structure of this
1455 // expression.
1456 ObjCMessageExpr *OldMsg =
1457 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1458 PseudoOp->getNumSemanticExprs() - 1));
1459
1460 // Because the rewriter doesn't allow us to rewrite rewritten code,
1461 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001462 Expr *Base;
1463 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001464 {
1465 DisableReplaceStmtScope S(*this);
1466
1467 // Rebuild the base expression if we have one.
1468 Base = 0;
1469 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1470 Base = OldMsg->getInstanceReceiver();
1471 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1472 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1473 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001474
1475 unsigned numArgs = OldMsg->getNumArgs();
1476 for (unsigned i = 0; i < numArgs; i++) {
1477 Expr *Arg = OldMsg->getArg(i);
1478 if (isa<OpaqueValueExpr>(Arg))
1479 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1480 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1481 Args.push_back(Arg);
1482 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001483 }
1484
1485 // TODO: avoid this copy.
1486 SmallVector<SourceLocation, 1> SelLocs;
1487 OldMsg->getSelectorLocs(SelLocs);
1488
1489 ObjCMessageExpr *NewMsg = 0;
1490 switch (OldMsg->getReceiverKind()) {
1491 case ObjCMessageExpr::Class:
1492 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1493 OldMsg->getValueKind(),
1494 OldMsg->getLeftLoc(),
1495 OldMsg->getClassReceiverTypeInfo(),
1496 OldMsg->getSelector(),
1497 SelLocs,
1498 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001499 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001500 OldMsg->getRightLoc(),
1501 OldMsg->isImplicit());
1502 break;
1503
1504 case ObjCMessageExpr::Instance:
1505 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1506 OldMsg->getValueKind(),
1507 OldMsg->getLeftLoc(),
1508 Base,
1509 OldMsg->getSelector(),
1510 SelLocs,
1511 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001512 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001513 OldMsg->getRightLoc(),
1514 OldMsg->isImplicit());
1515 break;
1516
1517 case ObjCMessageExpr::SuperClass:
1518 case ObjCMessageExpr::SuperInstance:
1519 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1520 OldMsg->getValueKind(),
1521 OldMsg->getLeftLoc(),
1522 OldMsg->getSuperLoc(),
1523 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1524 OldMsg->getSuperType(),
1525 OldMsg->getSelector(),
1526 SelLocs,
1527 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001528 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001529 OldMsg->getRightLoc(),
1530 OldMsg->isImplicit());
1531 break;
1532 }
1533
1534 Stmt *Replacement = SynthMessageExpr(NewMsg);
1535 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1536 return Replacement;
1537}
1538
1539Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1540 SourceRange OldRange = PseudoOp->getSourceRange();
1541
1542 // We just magically know some things about the structure of this
1543 // expression.
1544 ObjCMessageExpr *OldMsg =
1545 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1546
1547 // Because the rewriter doesn't allow us to rewrite rewritten code,
1548 // we need to suppress rewriting the sub-statements.
1549 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001550 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001551 {
1552 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001553 // Rebuild the base expression if we have one.
1554 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1555 Base = OldMsg->getInstanceReceiver();
1556 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1557 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1558 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001559 unsigned numArgs = OldMsg->getNumArgs();
1560 for (unsigned i = 0; i < numArgs; i++) {
1561 Expr *Arg = OldMsg->getArg(i);
1562 if (isa<OpaqueValueExpr>(Arg))
1563 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1564 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1565 Args.push_back(Arg);
1566 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001567 }
1568
1569 // Intentionally empty.
1570 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001571
1572 ObjCMessageExpr *NewMsg = 0;
1573 switch (OldMsg->getReceiverKind()) {
1574 case ObjCMessageExpr::Class:
1575 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1576 OldMsg->getValueKind(),
1577 OldMsg->getLeftLoc(),
1578 OldMsg->getClassReceiverTypeInfo(),
1579 OldMsg->getSelector(),
1580 SelLocs,
1581 OldMsg->getMethodDecl(),
1582 Args,
1583 OldMsg->getRightLoc(),
1584 OldMsg->isImplicit());
1585 break;
1586
1587 case ObjCMessageExpr::Instance:
1588 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1589 OldMsg->getValueKind(),
1590 OldMsg->getLeftLoc(),
1591 Base,
1592 OldMsg->getSelector(),
1593 SelLocs,
1594 OldMsg->getMethodDecl(),
1595 Args,
1596 OldMsg->getRightLoc(),
1597 OldMsg->isImplicit());
1598 break;
1599
1600 case ObjCMessageExpr::SuperClass:
1601 case ObjCMessageExpr::SuperInstance:
1602 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1603 OldMsg->getValueKind(),
1604 OldMsg->getLeftLoc(),
1605 OldMsg->getSuperLoc(),
1606 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1607 OldMsg->getSuperType(),
1608 OldMsg->getSelector(),
1609 SelLocs,
1610 OldMsg->getMethodDecl(),
1611 Args,
1612 OldMsg->getRightLoc(),
1613 OldMsg->isImplicit());
1614 break;
1615 }
1616
1617 Stmt *Replacement = SynthMessageExpr(NewMsg);
1618 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1619 return Replacement;
1620}
1621
1622/// SynthCountByEnumWithState - To print:
1623/// ((unsigned int (*)
1624/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1625/// (void *)objc_msgSend)((id)l_collection,
1626/// sel_registerName(
1627/// "countByEnumeratingWithState:objects:count:"),
1628/// &enumState,
1629/// (id *)__rw_items, (unsigned int)16)
1630///
1631void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1632 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1633 "id *, unsigned int))(void *)objc_msgSend)";
1634 buf += "\n\t\t";
1635 buf += "((id)l_collection,\n\t\t";
1636 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1637 buf += "\n\t\t";
1638 buf += "&enumState, "
1639 "(id *)__rw_items, (unsigned int)16)";
1640}
1641
1642/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1643/// statement to exit to its outer synthesized loop.
1644///
1645Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1646 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1647 return S;
1648 // replace break with goto __break_label
1649 std::string buf;
1650
1651 SourceLocation startLoc = S->getLocStart();
1652 buf = "goto __break_label_";
1653 buf += utostr(ObjCBcLabelNo.back());
1654 ReplaceText(startLoc, strlen("break"), buf);
1655
1656 return 0;
1657}
1658
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001659void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1660 SourceLocation Loc,
1661 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001662 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001663 LineString += "\n#line ";
1664 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1665 LineString += utostr(PLoc.getLine());
1666 LineString += " \"";
1667 LineString += Lexer::Stringify(PLoc.getFilename());
1668 LineString += "\"\n";
1669 }
1670}
1671
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001672/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1673/// statement to continue with its inner synthesized loop.
1674///
1675Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1676 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1677 return S;
1678 // replace continue with goto __continue_label
1679 std::string buf;
1680
1681 SourceLocation startLoc = S->getLocStart();
1682 buf = "goto __continue_label_";
1683 buf += utostr(ObjCBcLabelNo.back());
1684 ReplaceText(startLoc, strlen("continue"), buf);
1685
1686 return 0;
1687}
1688
1689/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1690/// It rewrites:
1691/// for ( type elem in collection) { stmts; }
1692
1693/// Into:
1694/// {
1695/// type elem;
1696/// struct __objcFastEnumerationState enumState = { 0 };
1697/// id __rw_items[16];
1698/// id l_collection = (id)collection;
1699/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1700/// objects:__rw_items count:16];
1701/// if (limit) {
1702/// unsigned long startMutations = *enumState.mutationsPtr;
1703/// do {
1704/// unsigned long counter = 0;
1705/// do {
1706/// if (startMutations != *enumState.mutationsPtr)
1707/// objc_enumerationMutation(l_collection);
1708/// elem = (type)enumState.itemsPtr[counter++];
1709/// stmts;
1710/// __continue_label: ;
1711/// } while (counter < limit);
1712/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1713/// objects:__rw_items count:16]);
1714/// elem = nil;
1715/// __break_label: ;
1716/// }
1717/// else
1718/// elem = nil;
1719/// }
1720///
1721Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1722 SourceLocation OrigEnd) {
1723 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1724 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1725 "ObjCForCollectionStmt Statement stack mismatch");
1726 assert(!ObjCBcLabelNo.empty() &&
1727 "ObjCForCollectionStmt - Label No stack empty");
1728
1729 SourceLocation startLoc = S->getLocStart();
1730 const char *startBuf = SM->getCharacterData(startLoc);
1731 StringRef elementName;
1732 std::string elementTypeAsString;
1733 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001734 // line directive first.
1735 SourceLocation ForEachLoc = S->getForLoc();
1736 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1737 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001738 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1739 // type elem;
1740 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1741 QualType ElementType = cast<ValueDecl>(D)->getType();
1742 if (ElementType->isObjCQualifiedIdType() ||
1743 ElementType->isObjCQualifiedInterfaceType())
1744 // Simply use 'id' for all qualified types.
1745 elementTypeAsString = "id";
1746 else
1747 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1748 buf += elementTypeAsString;
1749 buf += " ";
1750 elementName = D->getName();
1751 buf += elementName;
1752 buf += ";\n\t";
1753 }
1754 else {
1755 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1756 elementName = DR->getDecl()->getName();
1757 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1758 if (VD->getType()->isObjCQualifiedIdType() ||
1759 VD->getType()->isObjCQualifiedInterfaceType())
1760 // Simply use 'id' for all qualified types.
1761 elementTypeAsString = "id";
1762 else
1763 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1764 }
1765
1766 // struct __objcFastEnumerationState enumState = { 0 };
1767 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1768 // id __rw_items[16];
1769 buf += "id __rw_items[16];\n\t";
1770 // id l_collection = (id)
1771 buf += "id l_collection = (id)";
1772 // Find start location of 'collection' the hard way!
1773 const char *startCollectionBuf = startBuf;
1774 startCollectionBuf += 3; // skip 'for'
1775 startCollectionBuf = strchr(startCollectionBuf, '(');
1776 startCollectionBuf++; // skip '('
1777 // find 'in' and skip it.
1778 while (*startCollectionBuf != ' ' ||
1779 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1780 (*(startCollectionBuf+3) != ' ' &&
1781 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1782 startCollectionBuf++;
1783 startCollectionBuf += 3;
1784
1785 // Replace: "for (type element in" with string constructed thus far.
1786 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1787 // Replace ')' in for '(' type elem in collection ')' with ';'
1788 SourceLocation rightParenLoc = S->getRParenLoc();
1789 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1790 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1791 buf = ";\n\t";
1792
1793 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1794 // objects:__rw_items count:16];
1795 // which is synthesized into:
1796 // unsigned int limit =
1797 // ((unsigned int (*)
1798 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1799 // (void *)objc_msgSend)((id)l_collection,
1800 // sel_registerName(
1801 // "countByEnumeratingWithState:objects:count:"),
1802 // (struct __objcFastEnumerationState *)&state,
1803 // (id *)__rw_items, (unsigned int)16);
1804 buf += "unsigned long limit =\n\t\t";
1805 SynthCountByEnumWithState(buf);
1806 buf += ";\n\t";
1807 /// if (limit) {
1808 /// unsigned long startMutations = *enumState.mutationsPtr;
1809 /// do {
1810 /// unsigned long counter = 0;
1811 /// do {
1812 /// if (startMutations != *enumState.mutationsPtr)
1813 /// objc_enumerationMutation(l_collection);
1814 /// elem = (type)enumState.itemsPtr[counter++];
1815 buf += "if (limit) {\n\t";
1816 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1817 buf += "do {\n\t\t";
1818 buf += "unsigned long counter = 0;\n\t\t";
1819 buf += "do {\n\t\t\t";
1820 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1821 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1822 buf += elementName;
1823 buf += " = (";
1824 buf += elementTypeAsString;
1825 buf += ")enumState.itemsPtr[counter++];";
1826 // Replace ')' in for '(' type elem in collection ')' with all of these.
1827 ReplaceText(lparenLoc, 1, buf);
1828
1829 /// __continue_label: ;
1830 /// } while (counter < limit);
1831 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1832 /// objects:__rw_items count:16]);
1833 /// elem = nil;
1834 /// __break_label: ;
1835 /// }
1836 /// else
1837 /// elem = nil;
1838 /// }
1839 ///
1840 buf = ";\n\t";
1841 buf += "__continue_label_";
1842 buf += utostr(ObjCBcLabelNo.back());
1843 buf += ": ;";
1844 buf += "\n\t\t";
1845 buf += "} while (counter < limit);\n\t";
1846 buf += "} while (limit = ";
1847 SynthCountByEnumWithState(buf);
1848 buf += ");\n\t";
1849 buf += elementName;
1850 buf += " = ((";
1851 buf += elementTypeAsString;
1852 buf += ")0);\n\t";
1853 buf += "__break_label_";
1854 buf += utostr(ObjCBcLabelNo.back());
1855 buf += ": ;\n\t";
1856 buf += "}\n\t";
1857 buf += "else\n\t\t";
1858 buf += elementName;
1859 buf += " = ((";
1860 buf += elementTypeAsString;
1861 buf += ")0);\n\t";
1862 buf += "}\n";
1863
1864 // Insert all these *after* the statement body.
1865 // FIXME: If this should support Obj-C++, support CXXTryStmt
1866 if (isa<CompoundStmt>(S->getBody())) {
1867 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1868 InsertText(endBodyLoc, buf);
1869 } else {
1870 /* Need to treat single statements specially. For example:
1871 *
1872 * for (A *a in b) if (stuff()) break;
1873 * for (A *a in b) xxxyy;
1874 *
1875 * The following code simply scans ahead to the semi to find the actual end.
1876 */
1877 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1878 const char *semiBuf = strchr(stmtBuf, ';');
1879 assert(semiBuf && "Can't find ';'");
1880 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1881 InsertText(endBodyLoc, buf);
1882 }
1883 Stmts.pop_back();
1884 ObjCBcLabelNo.pop_back();
1885 return 0;
1886}
1887
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001888static void Write_RethrowObject(std::string &buf) {
1889 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1890 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1891 buf += "\tid rethrow;\n";
1892 buf += "\t} _fin_force_rethow(_rethrow);";
1893}
1894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001895/// RewriteObjCSynchronizedStmt -
1896/// This routine rewrites @synchronized(expr) stmt;
1897/// into:
1898/// objc_sync_enter(expr);
1899/// @try stmt @finally { objc_sync_exit(expr); }
1900///
1901Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1902 // Get the start location and compute the semi location.
1903 SourceLocation startLoc = S->getLocStart();
1904 const char *startBuf = SM->getCharacterData(startLoc);
1905
1906 assert((*startBuf == '@') && "bogus @synchronized location");
1907
1908 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001909 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1910 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1911 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001913 const char *lparenBuf = startBuf;
1914 while (*lparenBuf != '(') lparenBuf++;
1915 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001916
1917 buf = "; objc_sync_enter(_sync_obj);\n";
1918 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1919 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1920 buf += "\n\tid sync_exit;";
1921 buf += "\n\t} _sync_exit(_sync_obj);\n";
1922
1923 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1924 // the sync expression is typically a message expression that's already
1925 // been rewritten! (which implies the SourceLocation's are invalid).
1926 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1927 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1928 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1929 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1930
1931 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1932 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1933 assert (*LBraceLocBuf == '{');
1934 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001935
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001936 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001937 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1938 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001939
1940 buf = "} catch (id e) {_rethrow = e;}\n";
1941 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001942 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001943 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001944
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001945 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001946
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001947 return 0;
1948}
1949
1950void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1951{
1952 // Perform a bottom up traversal of all children.
1953 for (Stmt::child_range CI = S->children(); CI; ++CI)
1954 if (*CI)
1955 WarnAboutReturnGotoStmts(*CI);
1956
1957 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1958 Diags.Report(Context->getFullLoc(S->getLocStart()),
1959 TryFinallyContainsReturnDiag);
1960 }
1961 return;
1962}
1963
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001964Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1965 SourceLocation startLoc = S->getAtLoc();
1966 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001967 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1968 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001969
1970 return 0;
1971}
1972
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001973Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001974 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001975 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001976 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001977 SourceLocation TryLocation = S->getAtTryLoc();
1978 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001979
1980 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001981 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001982 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001983 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001984 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001985 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001986 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001987 // Get the start location and compute the semi location.
1988 SourceLocation startLoc = S->getLocStart();
1989 const char *startBuf = SM->getCharacterData(startLoc);
1990
1991 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001992 if (finalStmt)
1993 ReplaceText(startLoc, 1, buf);
1994 else
1995 // @try -> try
1996 ReplaceText(startLoc, 1, "");
1997
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001998 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1999 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002000 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002001
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002002 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002003 bool AtRemoved = false;
2004 if (catchDecl) {
2005 QualType t = catchDecl->getType();
2006 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2007 // Should be a pointer to a class.
2008 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2009 if (IDecl) {
2010 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002011 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2012
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002013 startBuf = SM->getCharacterData(startLoc);
2014 assert((*startBuf == '@') && "bogus @catch location");
2015 SourceLocation rParenLoc = Catch->getRParenLoc();
2016 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2017
2018 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002019 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002020 Result += " *_"; Result += catchDecl->getNameAsString();
2021 Result += ")";
2022 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2023 // Foo *e = (Foo *)_e;
2024 Result.clear();
2025 Result = "{ ";
2026 Result += IDecl->getNameAsString();
2027 Result += " *"; Result += catchDecl->getNameAsString();
2028 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2029 Result += "_"; Result += catchDecl->getNameAsString();
2030
2031 Result += "; ";
2032 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2033 ReplaceText(lBraceLoc, 1, Result);
2034 AtRemoved = true;
2035 }
2036 }
2037 }
2038 if (!AtRemoved)
2039 // @catch -> catch
2040 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002041
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002042 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002043 if (finalStmt) {
2044 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002045 SourceLocation FinallyLoc = finalStmt->getLocStart();
2046
2047 if (noCatch) {
2048 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2049 buf += "catch (id e) {_rethrow = e;}\n";
2050 }
2051 else {
2052 buf += "}\n";
2053 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2054 buf += "catch (id e) {_rethrow = e;}\n";
2055 }
2056
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002057 SourceLocation startFinalLoc = finalStmt->getLocStart();
2058 ReplaceText(startFinalLoc, 8, buf);
2059 Stmt *body = finalStmt->getFinallyBody();
2060 SourceLocation startFinalBodyLoc = body->getLocStart();
2061 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002062 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002063 ReplaceText(startFinalBodyLoc, 1, buf);
2064
2065 SourceLocation endFinalBodyLoc = body->getLocEnd();
2066 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002067 // Now check for any return/continue/go statements within the @try.
2068 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002069 }
2070
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002071 return 0;
2072}
2073
2074// This can't be done with ReplaceStmt(S, ThrowExpr), since
2075// the throw expression is typically a message expression that's already
2076// been rewritten! (which implies the SourceLocation's are invalid).
2077Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2078 // Get the start location and compute the semi location.
2079 SourceLocation startLoc = S->getLocStart();
2080 const char *startBuf = SM->getCharacterData(startLoc);
2081
2082 assert((*startBuf == '@') && "bogus @throw location");
2083
2084 std::string buf;
2085 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2086 if (S->getThrowExpr())
2087 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002088 else
2089 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002090
2091 // handle "@ throw" correctly.
2092 const char *wBuf = strchr(startBuf, 'w');
2093 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2094 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2095
2096 const char *semiBuf = strchr(startBuf, ';');
2097 assert((*semiBuf == ';') && "@throw: can't find ';'");
2098 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002099 if (S->getThrowExpr())
2100 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002101 return 0;
2102}
2103
2104Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2105 // Create a new string expression.
2106 QualType StrType = Context->getPointerType(Context->CharTy);
2107 std::string StrEncoding;
2108 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2109 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2110 StringLiteral::Ascii, false,
2111 StrType, SourceLocation());
2112 ReplaceStmt(Exp, Replacement);
2113
2114 // Replace this subexpr in the parent.
2115 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2116 return Replacement;
2117}
2118
2119Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2120 if (!SelGetUidFunctionDecl)
2121 SynthSelGetUidFunctionDecl();
2122 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2123 // Create a call to sel_registerName("selName").
2124 SmallVector<Expr*, 8> SelExprs;
2125 QualType argType = Context->getPointerType(Context->CharTy);
2126 SelExprs.push_back(StringLiteral::Create(*Context,
2127 Exp->getSelector().getAsString(),
2128 StringLiteral::Ascii, false,
2129 argType, SourceLocation()));
2130 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2131 &SelExprs[0], SelExprs.size());
2132 ReplaceStmt(Exp, SelExp);
2133 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2134 return SelExp;
2135}
2136
2137CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2138 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2139 SourceLocation EndLoc) {
2140 // Get the type, we will need to reference it in a couple spots.
2141 QualType msgSendType = FD->getType();
2142
2143 // Create a reference to the objc_msgSend() declaration.
2144 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002145 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002146
2147 // Now, we cast the reference to a pointer to the objc_msgSend type.
2148 QualType pToFunc = Context->getPointerType(msgSendType);
2149 ImplicitCastExpr *ICE =
2150 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2151 DRE, 0, VK_RValue);
2152
2153 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2154
2155 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002156 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002157 FT->getCallResultType(*Context),
2158 VK_RValue, EndLoc);
2159 return Exp;
2160}
2161
2162static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2163 const char *&startRef, const char *&endRef) {
2164 while (startBuf < endBuf) {
2165 if (*startBuf == '<')
2166 startRef = startBuf; // mark the start.
2167 if (*startBuf == '>') {
2168 if (startRef && *startRef == '<') {
2169 endRef = startBuf; // mark the end.
2170 return true;
2171 }
2172 return false;
2173 }
2174 startBuf++;
2175 }
2176 return false;
2177}
2178
2179static void scanToNextArgument(const char *&argRef) {
2180 int angle = 0;
2181 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2182 if (*argRef == '<')
2183 angle++;
2184 else if (*argRef == '>')
2185 angle--;
2186 argRef++;
2187 }
2188 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2189}
2190
2191bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2192 if (T->isObjCQualifiedIdType())
2193 return true;
2194 if (const PointerType *PT = T->getAs<PointerType>()) {
2195 if (PT->getPointeeType()->isObjCQualifiedIdType())
2196 return true;
2197 }
2198 if (T->isObjCObjectPointerType()) {
2199 T = T->getPointeeType();
2200 return T->isObjCQualifiedInterfaceType();
2201 }
2202 if (T->isArrayType()) {
2203 QualType ElemTy = Context->getBaseElementType(T);
2204 return needToScanForQualifiers(ElemTy);
2205 }
2206 return false;
2207}
2208
2209void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2210 QualType Type = E->getType();
2211 if (needToScanForQualifiers(Type)) {
2212 SourceLocation Loc, EndLoc;
2213
2214 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2215 Loc = ECE->getLParenLoc();
2216 EndLoc = ECE->getRParenLoc();
2217 } else {
2218 Loc = E->getLocStart();
2219 EndLoc = E->getLocEnd();
2220 }
2221 // This will defend against trying to rewrite synthesized expressions.
2222 if (Loc.isInvalid() || EndLoc.isInvalid())
2223 return;
2224
2225 const char *startBuf = SM->getCharacterData(Loc);
2226 const char *endBuf = SM->getCharacterData(EndLoc);
2227 const char *startRef = 0, *endRef = 0;
2228 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2229 // Get the locations of the startRef, endRef.
2230 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2231 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2232 // Comment out the protocol references.
2233 InsertText(LessLoc, "/*");
2234 InsertText(GreaterLoc, "*/");
2235 }
2236 }
2237}
2238
2239void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2240 SourceLocation Loc;
2241 QualType Type;
2242 const FunctionProtoType *proto = 0;
2243 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2244 Loc = VD->getLocation();
2245 Type = VD->getType();
2246 }
2247 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2248 Loc = FD->getLocation();
2249 // Check for ObjC 'id' and class types that have been adorned with protocol
2250 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2251 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2252 assert(funcType && "missing function type");
2253 proto = dyn_cast<FunctionProtoType>(funcType);
2254 if (!proto)
2255 return;
2256 Type = proto->getResultType();
2257 }
2258 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2259 Loc = FD->getLocation();
2260 Type = FD->getType();
2261 }
2262 else
2263 return;
2264
2265 if (needToScanForQualifiers(Type)) {
2266 // Since types are unique, we need to scan the buffer.
2267
2268 const char *endBuf = SM->getCharacterData(Loc);
2269 const char *startBuf = endBuf;
2270 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2271 startBuf--; // scan backward (from the decl location) for return type.
2272 const char *startRef = 0, *endRef = 0;
2273 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2274 // Get the locations of the startRef, endRef.
2275 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2276 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2277 // Comment out the protocol references.
2278 InsertText(LessLoc, "/*");
2279 InsertText(GreaterLoc, "*/");
2280 }
2281 }
2282 if (!proto)
2283 return; // most likely, was a variable
2284 // Now check arguments.
2285 const char *startBuf = SM->getCharacterData(Loc);
2286 const char *startFuncBuf = startBuf;
2287 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2288 if (needToScanForQualifiers(proto->getArgType(i))) {
2289 // Since types are unique, we need to scan the buffer.
2290
2291 const char *endBuf = startBuf;
2292 // scan forward (from the decl location) for argument types.
2293 scanToNextArgument(endBuf);
2294 const char *startRef = 0, *endRef = 0;
2295 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2296 // Get the locations of the startRef, endRef.
2297 SourceLocation LessLoc =
2298 Loc.getLocWithOffset(startRef-startFuncBuf);
2299 SourceLocation GreaterLoc =
2300 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2301 // Comment out the protocol references.
2302 InsertText(LessLoc, "/*");
2303 InsertText(GreaterLoc, "*/");
2304 }
2305 startBuf = ++endBuf;
2306 }
2307 else {
2308 // If the function name is derived from a macro expansion, then the
2309 // argument buffer will not follow the name. Need to speak with Chris.
2310 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2311 startBuf++; // scan forward (from the decl location) for argument types.
2312 startBuf++;
2313 }
2314 }
2315}
2316
2317void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2318 QualType QT = ND->getType();
2319 const Type* TypePtr = QT->getAs<Type>();
2320 if (!isa<TypeOfExprType>(TypePtr))
2321 return;
2322 while (isa<TypeOfExprType>(TypePtr)) {
2323 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2324 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2325 TypePtr = QT->getAs<Type>();
2326 }
2327 // FIXME. This will not work for multiple declarators; as in:
2328 // __typeof__(a) b,c,d;
2329 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2330 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2331 const char *startBuf = SM->getCharacterData(DeclLoc);
2332 if (ND->getInit()) {
2333 std::string Name(ND->getNameAsString());
2334 TypeAsString += " " + Name + " = ";
2335 Expr *E = ND->getInit();
2336 SourceLocation startLoc;
2337 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2338 startLoc = ECE->getLParenLoc();
2339 else
2340 startLoc = E->getLocStart();
2341 startLoc = SM->getExpansionLoc(startLoc);
2342 const char *endBuf = SM->getCharacterData(startLoc);
2343 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2344 }
2345 else {
2346 SourceLocation X = ND->getLocEnd();
2347 X = SM->getExpansionLoc(X);
2348 const char *endBuf = SM->getCharacterData(X);
2349 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2350 }
2351}
2352
2353// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2354void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2355 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2356 SmallVector<QualType, 16> ArgTys;
2357 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2358 QualType getFuncType =
2359 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2360 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002361 SourceLocation(),
2362 SourceLocation(),
2363 SelGetUidIdent, getFuncType, 0,
2364 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365}
2366
2367void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2368 // declared in <objc/objc.h>
2369 if (FD->getIdentifier() &&
2370 FD->getName() == "sel_registerName") {
2371 SelGetUidFunctionDecl = FD;
2372 return;
2373 }
2374 RewriteObjCQualifiedInterfaceTypes(FD);
2375}
2376
2377void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2378 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2379 const char *argPtr = TypeString.c_str();
2380 if (!strchr(argPtr, '^')) {
2381 Str += TypeString;
2382 return;
2383 }
2384 while (*argPtr) {
2385 Str += (*argPtr == '^' ? '*' : *argPtr);
2386 argPtr++;
2387 }
2388}
2389
2390// FIXME. Consolidate this routine with RewriteBlockPointerType.
2391void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2392 ValueDecl *VD) {
2393 QualType Type = VD->getType();
2394 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2395 const char *argPtr = TypeString.c_str();
2396 int paren = 0;
2397 while (*argPtr) {
2398 switch (*argPtr) {
2399 case '(':
2400 Str += *argPtr;
2401 paren++;
2402 break;
2403 case ')':
2404 Str += *argPtr;
2405 paren--;
2406 break;
2407 case '^':
2408 Str += '*';
2409 if (paren == 1)
2410 Str += VD->getNameAsString();
2411 break;
2412 default:
2413 Str += *argPtr;
2414 break;
2415 }
2416 argPtr++;
2417 }
2418}
2419
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002420void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2421 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2422 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2423 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2424 if (!proto)
2425 return;
2426 QualType Type = proto->getResultType();
2427 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2428 FdStr += " ";
2429 FdStr += FD->getName();
2430 FdStr += "(";
2431 unsigned numArgs = proto->getNumArgs();
2432 for (unsigned i = 0; i < numArgs; i++) {
2433 QualType ArgType = proto->getArgType(i);
2434 RewriteBlockPointerType(FdStr, ArgType);
2435 if (i+1 < numArgs)
2436 FdStr += ", ";
2437 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002438 if (FD->isVariadic()) {
2439 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2440 }
2441 else
2442 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002443 InsertText(FunLocStart, FdStr);
2444}
2445
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002446// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002447void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2448 if (SuperContructorFunctionDecl)
2449 return;
2450 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2451 SmallVector<QualType, 16> ArgTys;
2452 QualType argT = Context->getObjCIdType();
2453 assert(!argT.isNull() && "Can't find 'id' type");
2454 ArgTys.push_back(argT);
2455 ArgTys.push_back(argT);
2456 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2457 &ArgTys[0], ArgTys.size());
2458 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002459 SourceLocation(),
2460 SourceLocation(),
2461 msgSendIdent, msgSendType,
2462 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002463}
2464
2465// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2466void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2467 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2468 SmallVector<QualType, 16> ArgTys;
2469 QualType argT = Context->getObjCIdType();
2470 assert(!argT.isNull() && "Can't find 'id' type");
2471 ArgTys.push_back(argT);
2472 argT = Context->getObjCSelType();
2473 assert(!argT.isNull() && "Can't find 'SEL' type");
2474 ArgTys.push_back(argT);
2475 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2476 &ArgTys[0], ArgTys.size(),
2477 true /*isVariadic*/);
2478 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002479 SourceLocation(),
2480 SourceLocation(),
2481 msgSendIdent, msgSendType, 0,
2482 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002483}
2484
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002485// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002486void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2487 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002488 SmallVector<QualType, 2> ArgTys;
2489 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002490 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002491 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002492 true /*isVariadic*/);
2493 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002494 SourceLocation(),
2495 SourceLocation(),
2496 msgSendIdent, msgSendType, 0,
2497 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002498}
2499
2500// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2501void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2502 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2503 SmallVector<QualType, 16> ArgTys;
2504 QualType argT = Context->getObjCIdType();
2505 assert(!argT.isNull() && "Can't find 'id' type");
2506 ArgTys.push_back(argT);
2507 argT = Context->getObjCSelType();
2508 assert(!argT.isNull() && "Can't find 'SEL' type");
2509 ArgTys.push_back(argT);
2510 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2511 &ArgTys[0], ArgTys.size(),
2512 true /*isVariadic*/);
2513 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002514 SourceLocation(),
2515 SourceLocation(),
2516 msgSendIdent, msgSendType, 0,
2517 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002518}
2519
2520// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002521// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002522void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2523 IdentifierInfo *msgSendIdent =
2524 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002525 SmallVector<QualType, 2> ArgTys;
2526 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002527 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002528 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002529 true /*isVariadic*/);
2530 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2531 SourceLocation(),
2532 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002533 msgSendIdent,
2534 msgSendType, 0,
2535 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002536}
2537
2538// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2539void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2540 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2541 SmallVector<QualType, 16> ArgTys;
2542 QualType argT = Context->getObjCIdType();
2543 assert(!argT.isNull() && "Can't find 'id' type");
2544 ArgTys.push_back(argT);
2545 argT = Context->getObjCSelType();
2546 assert(!argT.isNull() && "Can't find 'SEL' type");
2547 ArgTys.push_back(argT);
2548 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2549 &ArgTys[0], ArgTys.size(),
2550 true /*isVariadic*/);
2551 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002552 SourceLocation(),
2553 SourceLocation(),
2554 msgSendIdent, msgSendType, 0,
2555 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002556}
2557
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002558// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002559void RewriteModernObjC::SynthGetClassFunctionDecl() {
2560 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2561 SmallVector<QualType, 16> ArgTys;
2562 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002563 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002564 &ArgTys[0], ArgTys.size());
2565 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002566 SourceLocation(),
2567 SourceLocation(),
2568 getClassIdent, getClassType, 0,
2569 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002570}
2571
2572// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2573void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2574 IdentifierInfo *getSuperClassIdent =
2575 &Context->Idents.get("class_getSuperclass");
2576 SmallVector<QualType, 16> ArgTys;
2577 ArgTys.push_back(Context->getObjCClassType());
2578 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2579 &ArgTys[0], ArgTys.size());
2580 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2581 SourceLocation(),
2582 SourceLocation(),
2583 getSuperClassIdent,
2584 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002585 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002586}
2587
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002588// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002589void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2590 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2591 SmallVector<QualType, 16> ArgTys;
2592 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002593 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002594 &ArgTys[0], ArgTys.size());
2595 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002596 SourceLocation(),
2597 SourceLocation(),
2598 getClassIdent, getClassType,
2599 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002600}
2601
2602Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2603 QualType strType = getConstantStringStructType();
2604
2605 std::string S = "__NSConstantStringImpl_";
2606
2607 std::string tmpName = InFileName;
2608 unsigned i;
2609 for (i=0; i < tmpName.length(); i++) {
2610 char c = tmpName.at(i);
2611 // replace any non alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002612 if (!isAlphanumeric(c))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002613 tmpName[i] = '_';
2614 }
2615 S += tmpName;
2616 S += "_";
2617 S += utostr(NumObjCStringLiterals++);
2618
2619 Preamble += "static __NSConstantStringImpl " + S;
2620 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2621 Preamble += "0x000007c8,"; // utf8_str
2622 // The pretty printer for StringLiteral handles escape characters properly.
2623 std::string prettyBufS;
2624 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002625 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002626 Preamble += prettyBuf.str();
2627 Preamble += ",";
2628 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2629
2630 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2631 SourceLocation(), &Context->Idents.get(S),
2632 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002633 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002634 SourceLocation());
2635 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2636 Context->getPointerType(DRE->getType()),
2637 VK_RValue, OK_Ordinary,
2638 SourceLocation());
2639 // cast to NSConstantString *
2640 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2641 CK_CPointerToObjCPointerCast, Unop);
2642 ReplaceStmt(Exp, cast);
2643 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2644 return cast;
2645}
2646
Fariborz Jahanian55947042012-03-27 20:17:30 +00002647Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2648 unsigned IntSize =
2649 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2650
2651 Expr *FlagExp = IntegerLiteral::Create(*Context,
2652 llvm::APInt(IntSize, Exp->getValue()),
2653 Context->IntTy, Exp->getLocation());
2654 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2655 CK_BitCast, FlagExp);
2656 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2657 cast);
2658 ReplaceStmt(Exp, PE);
2659 return PE;
2660}
2661
Patrick Beardeb382ec2012-04-19 00:25:12 +00002662Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002663 // synthesize declaration of helper functions needed in this routine.
2664 if (!SelGetUidFunctionDecl)
2665 SynthSelGetUidFunctionDecl();
2666 // use objc_msgSend() for all.
2667 if (!MsgSendFunctionDecl)
2668 SynthMsgSendFunctionDecl();
2669 if (!GetClassFunctionDecl)
2670 SynthGetClassFunctionDecl();
2671
2672 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2673 SourceLocation StartLoc = Exp->getLocStart();
2674 SourceLocation EndLoc = Exp->getLocEnd();
2675
2676 // Synthesize a call to objc_msgSend().
2677 SmallVector<Expr*, 4> MsgExprs;
2678 SmallVector<Expr*, 4> ClsExprs;
2679 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002680
Patrick Beardeb382ec2012-04-19 00:25:12 +00002681 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2682 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2683 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002684
Patrick Beardeb382ec2012-04-19 00:25:12 +00002685 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002686 ClsExprs.push_back(StringLiteral::Create(*Context,
2687 clsName->getName(),
2688 StringLiteral::Ascii, false,
2689 argType, SourceLocation()));
2690 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2691 &ClsExprs[0],
2692 ClsExprs.size(),
2693 StartLoc, EndLoc);
2694 MsgExprs.push_back(Cls);
2695
Patrick Beardeb382ec2012-04-19 00:25:12 +00002696 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002697 // it will be the 2nd argument.
2698 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002699 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002700 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002701 StringLiteral::Ascii, false,
2702 argType, SourceLocation()));
2703 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2704 &SelExprs[0], SelExprs.size(),
2705 StartLoc, EndLoc);
2706 MsgExprs.push_back(SelExp);
2707
Patrick Beardeb382ec2012-04-19 00:25:12 +00002708 // User provided sub-expression is the 3rd, and last, argument.
2709 Expr *subExpr = Exp->getSubExpr();
2710 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002711 QualType type = ICE->getType();
2712 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2713 CastKind CK = CK_BitCast;
2714 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2715 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002716 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002717 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002718 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002719
2720 SmallVector<QualType, 4> ArgTypes;
2721 ArgTypes.push_back(Context->getObjCIdType());
2722 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002723 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2724 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002725 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002726
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002727 QualType returnType = Exp->getType();
2728 // Get the type, we will need to reference it in a couple spots.
2729 QualType msgSendType = MsgSendFlavor->getType();
2730
2731 // Create a reference to the objc_msgSend() declaration.
2732 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2733 VK_LValue, SourceLocation());
2734
2735 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002736 Context->getPointerType(Context->VoidTy),
2737 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002738
2739 // Now do the "normal" pointer to function cast.
2740 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002741 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2742 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002743 castType = Context->getPointerType(castType);
2744 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2745 cast);
2746
2747 // Don't forget the parens to enforce the proper binding.
2748 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2749
2750 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002751 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002752 FT->getResultType(), VK_RValue,
2753 EndLoc);
2754 ReplaceStmt(Exp, CE);
2755 return CE;
2756}
2757
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002758Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2759 // synthesize declaration of helper functions needed in this routine.
2760 if (!SelGetUidFunctionDecl)
2761 SynthSelGetUidFunctionDecl();
2762 // use objc_msgSend() for all.
2763 if (!MsgSendFunctionDecl)
2764 SynthMsgSendFunctionDecl();
2765 if (!GetClassFunctionDecl)
2766 SynthGetClassFunctionDecl();
2767
2768 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2769 SourceLocation StartLoc = Exp->getLocStart();
2770 SourceLocation EndLoc = Exp->getLocEnd();
2771
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002772 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002773 QualType IntQT = Context->IntTy;
2774 QualType NSArrayFType =
2775 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002776 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002777 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2778 DeclRefExpr *NSArrayDRE =
2779 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2780 SourceLocation());
2781
2782 SmallVector<Expr*, 16> InitExprs;
2783 unsigned NumElements = Exp->getNumElements();
2784 unsigned UnsignedIntSize =
2785 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2786 Expr *count = IntegerLiteral::Create(*Context,
2787 llvm::APInt(UnsignedIntSize, NumElements),
2788 Context->UnsignedIntTy, SourceLocation());
2789 InitExprs.push_back(count);
2790 for (unsigned i = 0; i < NumElements; i++)
2791 InitExprs.push_back(Exp->getElement(i));
2792 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002793 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002794 NSArrayFType, VK_LValue, SourceLocation());
2795
2796 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2797 SourceLocation(),
2798 &Context->Idents.get("arr"),
2799 Context->getPointerType(Context->VoidPtrTy), 0,
2800 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002801 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002802 MemberExpr *ArrayLiteralME =
2803 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2804 SourceLocation(),
2805 ARRFD->getType(), VK_LValue,
2806 OK_Ordinary);
2807 QualType ConstIdT = Context->getObjCIdType().withConst();
2808 CStyleCastExpr * ArrayLiteralObjects =
2809 NoTypeInfoCStyleCastExpr(Context,
2810 Context->getPointerType(ConstIdT),
2811 CK_BitCast,
2812 ArrayLiteralME);
2813
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002814 // Synthesize a call to objc_msgSend().
2815 SmallVector<Expr*, 32> MsgExprs;
2816 SmallVector<Expr*, 4> ClsExprs;
2817 QualType argType = Context->getPointerType(Context->CharTy);
2818 QualType expType = Exp->getType();
2819
2820 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2821 ObjCInterfaceDecl *Class =
2822 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2823
2824 IdentifierInfo *clsName = Class->getIdentifier();
2825 ClsExprs.push_back(StringLiteral::Create(*Context,
2826 clsName->getName(),
2827 StringLiteral::Ascii, false,
2828 argType, SourceLocation()));
2829 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2830 &ClsExprs[0],
2831 ClsExprs.size(),
2832 StartLoc, EndLoc);
2833 MsgExprs.push_back(Cls);
2834
2835 // Create a call to sel_registerName("arrayWithObjects:count:").
2836 // it will be the 2nd argument.
2837 SmallVector<Expr*, 4> SelExprs;
2838 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2839 SelExprs.push_back(StringLiteral::Create(*Context,
2840 ArrayMethod->getSelector().getAsString(),
2841 StringLiteral::Ascii, false,
2842 argType, SourceLocation()));
2843 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2844 &SelExprs[0], SelExprs.size(),
2845 StartLoc, EndLoc);
2846 MsgExprs.push_back(SelExp);
2847
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002848 // (const id [])objects
2849 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002850
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002851 // (NSUInteger)cnt
2852 Expr *cnt = IntegerLiteral::Create(*Context,
2853 llvm::APInt(UnsignedIntSize, NumElements),
2854 Context->UnsignedIntTy, SourceLocation());
2855 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002856
2857
2858 SmallVector<QualType, 4> ArgTypes;
2859 ArgTypes.push_back(Context->getObjCIdType());
2860 ArgTypes.push_back(Context->getObjCSelType());
2861 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2862 E = ArrayMethod->param_end(); PI != E; ++PI)
2863 ArgTypes.push_back((*PI)->getType());
2864
2865 QualType returnType = Exp->getType();
2866 // Get the type, we will need to reference it in a couple spots.
2867 QualType msgSendType = MsgSendFlavor->getType();
2868
2869 // Create a reference to the objc_msgSend() declaration.
2870 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2871 VK_LValue, SourceLocation());
2872
2873 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2874 Context->getPointerType(Context->VoidTy),
2875 CK_BitCast, DRE);
2876
2877 // Now do the "normal" pointer to function cast.
2878 QualType castType =
2879 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2880 ArrayMethod->isVariadic());
2881 castType = Context->getPointerType(castType);
2882 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2883 cast);
2884
2885 // Don't forget the parens to enforce the proper binding.
2886 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2887
2888 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002889 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002890 FT->getResultType(), VK_RValue,
2891 EndLoc);
2892 ReplaceStmt(Exp, CE);
2893 return CE;
2894}
2895
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002896Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2897 // synthesize declaration of helper functions needed in this routine.
2898 if (!SelGetUidFunctionDecl)
2899 SynthSelGetUidFunctionDecl();
2900 // use objc_msgSend() for all.
2901 if (!MsgSendFunctionDecl)
2902 SynthMsgSendFunctionDecl();
2903 if (!GetClassFunctionDecl)
2904 SynthGetClassFunctionDecl();
2905
2906 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2907 SourceLocation StartLoc = Exp->getLocStart();
2908 SourceLocation EndLoc = Exp->getLocEnd();
2909
2910 // Build the expression: __NSContainer_literal(int, ...).arr
2911 QualType IntQT = Context->IntTy;
2912 QualType NSDictFType =
2913 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2914 std::string NSDictFName("__NSContainer_literal");
2915 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2916 DeclRefExpr *NSDictDRE =
2917 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2918 SourceLocation());
2919
2920 SmallVector<Expr*, 16> KeyExprs;
2921 SmallVector<Expr*, 16> ValueExprs;
2922
2923 unsigned NumElements = Exp->getNumElements();
2924 unsigned UnsignedIntSize =
2925 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2926 Expr *count = IntegerLiteral::Create(*Context,
2927 llvm::APInt(UnsignedIntSize, NumElements),
2928 Context->UnsignedIntTy, SourceLocation());
2929 KeyExprs.push_back(count);
2930 ValueExprs.push_back(count);
2931 for (unsigned i = 0; i < NumElements; i++) {
2932 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2933 KeyExprs.push_back(Element.Key);
2934 ValueExprs.push_back(Element.Value);
2935 }
2936
2937 // (const id [])objects
2938 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002939 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002940 NSDictFType, VK_LValue, SourceLocation());
2941
2942 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2943 SourceLocation(),
2944 &Context->Idents.get("arr"),
2945 Context->getPointerType(Context->VoidPtrTy), 0,
2946 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002947 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002948 MemberExpr *DictLiteralValueME =
2949 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2950 SourceLocation(),
2951 ARRFD->getType(), VK_LValue,
2952 OK_Ordinary);
2953 QualType ConstIdT = Context->getObjCIdType().withConst();
2954 CStyleCastExpr * DictValueObjects =
2955 NoTypeInfoCStyleCastExpr(Context,
2956 Context->getPointerType(ConstIdT),
2957 CK_BitCast,
2958 DictLiteralValueME);
2959 // (const id <NSCopying> [])keys
2960 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002961 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002962 NSDictFType, VK_LValue, SourceLocation());
2963
2964 MemberExpr *DictLiteralKeyME =
2965 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2966 SourceLocation(),
2967 ARRFD->getType(), VK_LValue,
2968 OK_Ordinary);
2969
2970 CStyleCastExpr * DictKeyObjects =
2971 NoTypeInfoCStyleCastExpr(Context,
2972 Context->getPointerType(ConstIdT),
2973 CK_BitCast,
2974 DictLiteralKeyME);
2975
2976
2977
2978 // Synthesize a call to objc_msgSend().
2979 SmallVector<Expr*, 32> MsgExprs;
2980 SmallVector<Expr*, 4> ClsExprs;
2981 QualType argType = Context->getPointerType(Context->CharTy);
2982 QualType expType = Exp->getType();
2983
2984 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2985 ObjCInterfaceDecl *Class =
2986 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2987
2988 IdentifierInfo *clsName = Class->getIdentifier();
2989 ClsExprs.push_back(StringLiteral::Create(*Context,
2990 clsName->getName(),
2991 StringLiteral::Ascii, false,
2992 argType, SourceLocation()));
2993 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2994 &ClsExprs[0],
2995 ClsExprs.size(),
2996 StartLoc, EndLoc);
2997 MsgExprs.push_back(Cls);
2998
2999 // Create a call to sel_registerName("arrayWithObjects:count:").
3000 // it will be the 2nd argument.
3001 SmallVector<Expr*, 4> SelExprs;
3002 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
3003 SelExprs.push_back(StringLiteral::Create(*Context,
3004 DictMethod->getSelector().getAsString(),
3005 StringLiteral::Ascii, false,
3006 argType, SourceLocation()));
3007 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3008 &SelExprs[0], SelExprs.size(),
3009 StartLoc, EndLoc);
3010 MsgExprs.push_back(SelExp);
3011
3012 // (const id [])objects
3013 MsgExprs.push_back(DictValueObjects);
3014
3015 // (const id <NSCopying> [])keys
3016 MsgExprs.push_back(DictKeyObjects);
3017
3018 // (NSUInteger)cnt
3019 Expr *cnt = IntegerLiteral::Create(*Context,
3020 llvm::APInt(UnsignedIntSize, NumElements),
3021 Context->UnsignedIntTy, SourceLocation());
3022 MsgExprs.push_back(cnt);
3023
3024
3025 SmallVector<QualType, 8> ArgTypes;
3026 ArgTypes.push_back(Context->getObjCIdType());
3027 ArgTypes.push_back(Context->getObjCSelType());
3028 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3029 E = DictMethod->param_end(); PI != E; ++PI) {
3030 QualType T = (*PI)->getType();
3031 if (const PointerType* PT = T->getAs<PointerType>()) {
3032 QualType PointeeTy = PT->getPointeeType();
3033 convertToUnqualifiedObjCType(PointeeTy);
3034 T = Context->getPointerType(PointeeTy);
3035 }
3036 ArgTypes.push_back(T);
3037 }
3038
3039 QualType returnType = Exp->getType();
3040 // Get the type, we will need to reference it in a couple spots.
3041 QualType msgSendType = MsgSendFlavor->getType();
3042
3043 // Create a reference to the objc_msgSend() declaration.
3044 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3045 VK_LValue, SourceLocation());
3046
3047 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3048 Context->getPointerType(Context->VoidTy),
3049 CK_BitCast, DRE);
3050
3051 // Now do the "normal" pointer to function cast.
3052 QualType castType =
3053 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3054 DictMethod->isVariadic());
3055 castType = Context->getPointerType(castType);
3056 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3057 cast);
3058
3059 // Don't forget the parens to enforce the proper binding.
3060 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3061
3062 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003063 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003064 FT->getResultType(), VK_RValue,
3065 EndLoc);
3066 ReplaceStmt(Exp, CE);
3067 return CE;
3068}
3069
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003070// struct __rw_objc_super {
3071// struct objc_object *object; struct objc_object *superClass;
3072// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003073QualType RewriteModernObjC::getSuperStructType() {
3074 if (!SuperStructDecl) {
3075 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3076 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003077 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003078 QualType FieldTypes[2];
3079
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003080 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003081 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003082 // struct objc_object *superClass;
3083 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003084
3085 // Create fields
3086 for (unsigned i = 0; i < 2; ++i) {
3087 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3088 SourceLocation(),
3089 SourceLocation(), 0,
3090 FieldTypes[i], 0,
3091 /*BitWidth=*/0,
3092 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003093 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003094 }
3095
3096 SuperStructDecl->completeDefinition();
3097 }
3098 return Context->getTagDeclType(SuperStructDecl);
3099}
3100
3101QualType RewriteModernObjC::getConstantStringStructType() {
3102 if (!ConstantStringDecl) {
3103 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3104 SourceLocation(), SourceLocation(),
3105 &Context->Idents.get("__NSConstantStringImpl"));
3106 QualType FieldTypes[4];
3107
3108 // struct objc_object *receiver;
3109 FieldTypes[0] = Context->getObjCIdType();
3110 // int flags;
3111 FieldTypes[1] = Context->IntTy;
3112 // char *str;
3113 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3114 // long length;
3115 FieldTypes[3] = Context->LongTy;
3116
3117 // Create fields
3118 for (unsigned i = 0; i < 4; ++i) {
3119 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3120 ConstantStringDecl,
3121 SourceLocation(),
3122 SourceLocation(), 0,
3123 FieldTypes[i], 0,
3124 /*BitWidth=*/0,
3125 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003126 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003127 }
3128
3129 ConstantStringDecl->completeDefinition();
3130 }
3131 return Context->getTagDeclType(ConstantStringDecl);
3132}
3133
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003134/// getFunctionSourceLocation - returns start location of a function
3135/// definition. Complication arises when function has declared as
3136/// extern "C" or extern "C" {...}
3137static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3138 FunctionDecl *FD) {
3139 if (FD->isExternC() && !FD->isMain()) {
3140 const DeclContext *DC = FD->getDeclContext();
3141 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3142 // if it is extern "C" {...}, return function decl's own location.
3143 if (!LSD->getRBraceLoc().isValid())
3144 return LSD->getExternLoc();
3145 }
3146 if (FD->getStorageClassAsWritten() != SC_None)
3147 R.RewriteBlockLiteralFunctionDecl(FD);
3148 return FD->getTypeSpecStartLoc();
3149}
3150
Fariborz Jahanian96205962012-11-06 17:30:23 +00003151void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3152
3153 SourceLocation Location = D->getLocation();
3154
Fariborz Jahanianada71912013-02-08 00:27:34 +00003155 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003156 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003157 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3158 LineString += utostr(PLoc.getLine());
3159 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003160 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003161 if (isa<ObjCMethodDecl>(D))
3162 LineString += "\"";
3163 else LineString += "\"\n";
3164
3165 Location = D->getLocStart();
3166 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3167 if (FD->isExternC() && !FD->isMain()) {
3168 const DeclContext *DC = FD->getDeclContext();
3169 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3170 // if it is extern "C" {...}, return function decl's own location.
3171 if (!LSD->getRBraceLoc().isValid())
3172 Location = LSD->getExternLoc();
3173 }
3174 }
3175 InsertText(Location, LineString);
3176 }
3177}
3178
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003179/// SynthMsgSendStretCallExpr - This routine translates message expression
3180/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3181/// nil check on receiver must be performed before calling objc_msgSend_stret.
3182/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3183/// msgSendType - function type of objc_msgSend_stret(...)
3184/// returnType - Result type of the method being synthesized.
3185/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3186/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3187/// starting with receiver.
3188/// Method - Method being rewritten.
3189Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3190 QualType msgSendType,
3191 QualType returnType,
3192 SmallVectorImpl<QualType> &ArgTypes,
3193 SmallVectorImpl<Expr*> &MsgExprs,
3194 ObjCMethodDecl *Method) {
3195 // Now do the "normal" pointer to function cast.
3196 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3197 Method ? Method->isVariadic() : false);
3198 castType = Context->getPointerType(castType);
3199
3200 // build type for containing the objc_msgSend_stret object.
3201 static unsigned stretCount=0;
3202 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003203 std::string str =
3204 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3205 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003206 str += " {\n\t";
3207 str += name;
3208 str += "(id receiver, SEL sel";
3209 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003210 std::string ArgName = "arg"; ArgName += utostr(i);
3211 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3212 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003213 }
3214 // could be vararg.
3215 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003216 std::string ArgName = "arg"; ArgName += utostr(i);
3217 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3218 Context->getPrintingPolicy());
3219 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003220 }
3221
3222 str += ") {\n";
3223 str += "\t if (receiver == 0)\n";
3224 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3225 str += "\t else\n";
3226 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3227 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3228 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3229 str += ", arg"; str += utostr(i);
3230 }
3231 // could be vararg.
3232 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3233 str += ", arg"; str += utostr(i);
3234 }
3235
3236 str += ");\n";
3237 str += "\t}\n";
3238 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3239 str += " s;\n";
3240 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003241 SourceLocation FunLocStart;
3242 if (CurFunctionDef)
3243 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3244 else {
3245 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3246 FunLocStart = CurMethodDef->getLocStart();
3247 }
3248
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003249 InsertText(FunLocStart, str);
3250 ++stretCount;
3251
3252 // AST for __Stretn(receiver, args).s;
3253 IdentifierInfo *ID = &Context->Idents.get(name);
3254 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003255 SourceLocation(), ID, castType, 0,
3256 SC_Extern, SC_None, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003257 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3258 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003259 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003260 castType, VK_LValue, SourceLocation());
3261
3262 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3263 SourceLocation(),
3264 &Context->Idents.get("s"),
3265 returnType, 0,
3266 /*BitWidth=*/0, /*Mutable=*/true,
3267 ICIS_NoInit);
3268 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3269 FieldD->getType(), VK_LValue,
3270 OK_Ordinary);
3271
3272 return ME;
3273}
3274
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003275Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3276 SourceLocation StartLoc,
3277 SourceLocation EndLoc) {
3278 if (!SelGetUidFunctionDecl)
3279 SynthSelGetUidFunctionDecl();
3280 if (!MsgSendFunctionDecl)
3281 SynthMsgSendFunctionDecl();
3282 if (!MsgSendSuperFunctionDecl)
3283 SynthMsgSendSuperFunctionDecl();
3284 if (!MsgSendStretFunctionDecl)
3285 SynthMsgSendStretFunctionDecl();
3286 if (!MsgSendSuperStretFunctionDecl)
3287 SynthMsgSendSuperStretFunctionDecl();
3288 if (!MsgSendFpretFunctionDecl)
3289 SynthMsgSendFpretFunctionDecl();
3290 if (!GetClassFunctionDecl)
3291 SynthGetClassFunctionDecl();
3292 if (!GetSuperClassFunctionDecl)
3293 SynthGetSuperClassFunctionDecl();
3294 if (!GetMetaClassFunctionDecl)
3295 SynthGetMetaClassFunctionDecl();
3296
3297 // default to objc_msgSend().
3298 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3299 // May need to use objc_msgSend_stret() as well.
3300 FunctionDecl *MsgSendStretFlavor = 0;
3301 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3302 QualType resultType = mDecl->getResultType();
3303 if (resultType->isRecordType())
3304 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3305 else if (resultType->isRealFloatingType())
3306 MsgSendFlavor = MsgSendFpretFunctionDecl;
3307 }
3308
3309 // Synthesize a call to objc_msgSend().
3310 SmallVector<Expr*, 8> MsgExprs;
3311 switch (Exp->getReceiverKind()) {
3312 case ObjCMessageExpr::SuperClass: {
3313 MsgSendFlavor = MsgSendSuperFunctionDecl;
3314 if (MsgSendStretFlavor)
3315 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3316 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3317
3318 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3319
3320 SmallVector<Expr*, 4> InitExprs;
3321
3322 // set the receiver to self, the first argument to all methods.
3323 InitExprs.push_back(
3324 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3325 CK_BitCast,
3326 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003327 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003328 Context->getObjCIdType(),
3329 VK_RValue,
3330 SourceLocation()))
3331 ); // set the 'receiver'.
3332
3333 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3334 SmallVector<Expr*, 8> ClsExprs;
3335 QualType argType = Context->getPointerType(Context->CharTy);
3336 ClsExprs.push_back(StringLiteral::Create(*Context,
3337 ClassDecl->getIdentifier()->getName(),
3338 StringLiteral::Ascii, false,
3339 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003340 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003341 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3342 &ClsExprs[0],
3343 ClsExprs.size(),
3344 StartLoc,
3345 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003346 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003347 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003348 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3349 &ClsExprs[0], ClsExprs.size(),
3350 StartLoc, EndLoc);
3351
3352 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3353 // To turn off a warning, type-cast to 'id'
3354 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3355 NoTypeInfoCStyleCastExpr(Context,
3356 Context->getObjCIdType(),
3357 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003358 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003359 QualType superType = getSuperStructType();
3360 Expr *SuperRep;
3361
3362 if (LangOpts.MicrosoftExt) {
3363 SynthSuperContructorFunctionDecl();
3364 // Simulate a contructor call...
3365 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003366 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003367 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003368 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003369 superType, VK_LValue,
3370 SourceLocation());
3371 // The code for super is a little tricky to prevent collision with
3372 // the structure definition in the header. The rewriter has it's own
3373 // internal definition (__rw_objc_super) that is uses. This is why
3374 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003375 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003376 //
3377 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3378 Context->getPointerType(SuperRep->getType()),
3379 VK_RValue, OK_Ordinary,
3380 SourceLocation());
3381 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3382 Context->getPointerType(superType),
3383 CK_BitCast, SuperRep);
3384 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003385 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003386 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003387 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003388 SourceLocation());
3389 TypeSourceInfo *superTInfo
3390 = Context->getTrivialTypeSourceInfo(superType);
3391 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3392 superType, VK_LValue,
3393 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003394 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003395 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3396 Context->getPointerType(SuperRep->getType()),
3397 VK_RValue, OK_Ordinary,
3398 SourceLocation());
3399 }
3400 MsgExprs.push_back(SuperRep);
3401 break;
3402 }
3403
3404 case ObjCMessageExpr::Class: {
3405 SmallVector<Expr*, 8> ClsExprs;
3406 QualType argType = Context->getPointerType(Context->CharTy);
3407 ObjCInterfaceDecl *Class
3408 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3409 IdentifierInfo *clsName = Class->getIdentifier();
3410 ClsExprs.push_back(StringLiteral::Create(*Context,
3411 clsName->getName(),
3412 StringLiteral::Ascii, false,
3413 argType, SourceLocation()));
3414 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3415 &ClsExprs[0],
3416 ClsExprs.size(),
3417 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003418 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3419 Context->getObjCIdType(),
3420 CK_BitCast, Cls);
3421 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003422 break;
3423 }
3424
3425 case ObjCMessageExpr::SuperInstance:{
3426 MsgSendFlavor = MsgSendSuperFunctionDecl;
3427 if (MsgSendStretFlavor)
3428 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3429 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3430 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3431 SmallVector<Expr*, 4> InitExprs;
3432
3433 InitExprs.push_back(
3434 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3435 CK_BitCast,
3436 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003437 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003438 Context->getObjCIdType(),
3439 VK_RValue, SourceLocation()))
3440 ); // set the 'receiver'.
3441
3442 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3443 SmallVector<Expr*, 8> ClsExprs;
3444 QualType argType = Context->getPointerType(Context->CharTy);
3445 ClsExprs.push_back(StringLiteral::Create(*Context,
3446 ClassDecl->getIdentifier()->getName(),
3447 StringLiteral::Ascii, false, argType,
3448 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003449 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003450 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3451 &ClsExprs[0],
3452 ClsExprs.size(),
3453 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003454 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003455 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003456 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3457 &ClsExprs[0], ClsExprs.size(),
3458 StartLoc, EndLoc);
3459
3460 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3461 // To turn off a warning, type-cast to 'id'
3462 InitExprs.push_back(
3463 // set 'super class', using class_getSuperclass().
3464 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3465 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003466 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003467 QualType superType = getSuperStructType();
3468 Expr *SuperRep;
3469
3470 if (LangOpts.MicrosoftExt) {
3471 SynthSuperContructorFunctionDecl();
3472 // Simulate a contructor call...
3473 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003474 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003475 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003476 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003477 superType, VK_LValue, SourceLocation());
3478 // The code for super is a little tricky to prevent collision with
3479 // the structure definition in the header. The rewriter has it's own
3480 // internal definition (__rw_objc_super) that is uses. This is why
3481 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003482 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003483 //
3484 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3485 Context->getPointerType(SuperRep->getType()),
3486 VK_RValue, OK_Ordinary,
3487 SourceLocation());
3488 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3489 Context->getPointerType(superType),
3490 CK_BitCast, SuperRep);
3491 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003492 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003493 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003494 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003495 SourceLocation());
3496 TypeSourceInfo *superTInfo
3497 = Context->getTrivialTypeSourceInfo(superType);
3498 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3499 superType, VK_RValue, ILE,
3500 false);
3501 }
3502 MsgExprs.push_back(SuperRep);
3503 break;
3504 }
3505
3506 case ObjCMessageExpr::Instance: {
3507 // Remove all type-casts because it may contain objc-style types; e.g.
3508 // Foo<Proto> *.
3509 Expr *recExpr = Exp->getInstanceReceiver();
3510 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3511 recExpr = CE->getSubExpr();
3512 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3513 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3514 ? CK_BlockPointerToObjCPointerCast
3515 : CK_CPointerToObjCPointerCast;
3516
3517 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3518 CK, recExpr);
3519 MsgExprs.push_back(recExpr);
3520 break;
3521 }
3522 }
3523
3524 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3525 SmallVector<Expr*, 8> SelExprs;
3526 QualType argType = Context->getPointerType(Context->CharTy);
3527 SelExprs.push_back(StringLiteral::Create(*Context,
3528 Exp->getSelector().getAsString(),
3529 StringLiteral::Ascii, false,
3530 argType, SourceLocation()));
3531 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3532 &SelExprs[0], SelExprs.size(),
3533 StartLoc,
3534 EndLoc);
3535 MsgExprs.push_back(SelExp);
3536
3537 // Now push any user supplied arguments.
3538 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3539 Expr *userExpr = Exp->getArg(i);
3540 // Make all implicit casts explicit...ICE comes in handy:-)
3541 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3542 // Reuse the ICE type, it is exactly what the doctor ordered.
3543 QualType type = ICE->getType();
3544 if (needToScanForQualifiers(type))
3545 type = Context->getObjCIdType();
3546 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3547 (void)convertBlockPointerToFunctionPointer(type);
3548 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3549 CastKind CK;
3550 if (SubExpr->getType()->isIntegralType(*Context) &&
3551 type->isBooleanType()) {
3552 CK = CK_IntegralToBoolean;
3553 } else if (type->isObjCObjectPointerType()) {
3554 if (SubExpr->getType()->isBlockPointerType()) {
3555 CK = CK_BlockPointerToObjCPointerCast;
3556 } else if (SubExpr->getType()->isPointerType()) {
3557 CK = CK_CPointerToObjCPointerCast;
3558 } else {
3559 CK = CK_BitCast;
3560 }
3561 } else {
3562 CK = CK_BitCast;
3563 }
3564
3565 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3566 }
3567 // Make id<P...> cast into an 'id' cast.
3568 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3569 if (CE->getType()->isObjCQualifiedIdType()) {
3570 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3571 userExpr = CE->getSubExpr();
3572 CastKind CK;
3573 if (userExpr->getType()->isIntegralType(*Context)) {
3574 CK = CK_IntegralToPointer;
3575 } else if (userExpr->getType()->isBlockPointerType()) {
3576 CK = CK_BlockPointerToObjCPointerCast;
3577 } else if (userExpr->getType()->isPointerType()) {
3578 CK = CK_CPointerToObjCPointerCast;
3579 } else {
3580 CK = CK_BitCast;
3581 }
3582 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3583 CK, userExpr);
3584 }
3585 }
3586 MsgExprs.push_back(userExpr);
3587 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3588 // out the argument in the original expression (since we aren't deleting
3589 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3590 //Exp->setArg(i, 0);
3591 }
3592 // Generate the funky cast.
3593 CastExpr *cast;
3594 SmallVector<QualType, 8> ArgTypes;
3595 QualType returnType;
3596
3597 // Push 'id' and 'SEL', the 2 implicit arguments.
3598 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3599 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3600 else
3601 ArgTypes.push_back(Context->getObjCIdType());
3602 ArgTypes.push_back(Context->getObjCSelType());
3603 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3604 // Push any user argument types.
3605 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3606 E = OMD->param_end(); PI != E; ++PI) {
3607 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3608 ? Context->getObjCIdType()
3609 : (*PI)->getType();
3610 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3611 (void)convertBlockPointerToFunctionPointer(t);
3612 ArgTypes.push_back(t);
3613 }
3614 returnType = Exp->getType();
3615 convertToUnqualifiedObjCType(returnType);
3616 (void)convertBlockPointerToFunctionPointer(returnType);
3617 } else {
3618 returnType = Context->getObjCIdType();
3619 }
3620 // Get the type, we will need to reference it in a couple spots.
3621 QualType msgSendType = MsgSendFlavor->getType();
3622
3623 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003624 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003625 VK_LValue, SourceLocation());
3626
3627 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3628 // If we don't do this cast, we get the following bizarre warning/note:
3629 // xx.m:13: warning: function called through a non-compatible type
3630 // xx.m:13: note: if this code is reached, the program will abort
3631 cast = NoTypeInfoCStyleCastExpr(Context,
3632 Context->getPointerType(Context->VoidTy),
3633 CK_BitCast, DRE);
3634
3635 // Now do the "normal" pointer to function cast.
3636 QualType castType =
3637 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3638 // If we don't have a method decl, force a variadic cast.
3639 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3640 castType = Context->getPointerType(castType);
3641 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3642 cast);
3643
3644 // Don't forget the parens to enforce the proper binding.
3645 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3646
3647 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003648 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3649 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003650 Stmt *ReplacingStmt = CE;
3651 if (MsgSendStretFlavor) {
3652 // We have the method which returns a struct/union. Must also generate
3653 // call to objc_msgSend_stret and hang both varieties on a conditional
3654 // expression which dictate which one to envoke depending on size of
3655 // method's return type.
3656
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003657 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3658 msgSendType, returnType,
3659 ArgTypes, MsgExprs,
3660 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003661
3662 // Build sizeof(returnType)
3663 UnaryExprOrTypeTraitExpr *sizeofExpr =
3664 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3665 Context->getTrivialTypeSourceInfo(returnType),
3666 Context->getSizeType(), SourceLocation(),
3667 SourceLocation());
3668 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3669 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3670 // For X86 it is more complicated and some kind of target specific routine
3671 // is needed to decide what to do.
3672 unsigned IntSize =
3673 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3674 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3675 llvm::APInt(IntSize, 8),
3676 Context->IntTy,
3677 SourceLocation());
3678 BinaryOperator *lessThanExpr =
3679 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003680 VK_RValue, OK_Ordinary, SourceLocation(),
3681 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003682 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3683 ConditionalOperator *CondExpr =
3684 new (Context) ConditionalOperator(lessThanExpr,
3685 SourceLocation(), CE,
3686 SourceLocation(), STCE,
3687 returnType, VK_RValue, OK_Ordinary);
3688 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3689 CondExpr);
3690 }
3691 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3692 return ReplacingStmt;
3693}
3694
3695Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3696 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3697 Exp->getLocEnd());
3698
3699 // Now do the actual rewrite.
3700 ReplaceStmt(Exp, ReplacingStmt);
3701
3702 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3703 return ReplacingStmt;
3704}
3705
3706// typedef struct objc_object Protocol;
3707QualType RewriteModernObjC::getProtocolType() {
3708 if (!ProtocolTypeDecl) {
3709 TypeSourceInfo *TInfo
3710 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3711 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3712 SourceLocation(), SourceLocation(),
3713 &Context->Idents.get("Protocol"),
3714 TInfo);
3715 }
3716 return Context->getTypeDeclType(ProtocolTypeDecl);
3717}
3718
3719/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3720/// a synthesized/forward data reference (to the protocol's metadata).
3721/// The forward references (and metadata) are generated in
3722/// RewriteModernObjC::HandleTranslationUnit().
3723Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003724 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3725 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003726 IdentifierInfo *ID = &Context->Idents.get(Name);
3727 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3728 SourceLocation(), ID, getProtocolType(), 0,
3729 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003730 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3731 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003732 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3733 Context->getPointerType(DRE->getType()),
3734 VK_RValue, OK_Ordinary, SourceLocation());
3735 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3736 CK_BitCast,
3737 DerefExpr);
3738 ReplaceStmt(Exp, castExpr);
3739 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3740 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3741 return castExpr;
3742
3743}
3744
3745bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3746 const char *endBuf) {
3747 while (startBuf < endBuf) {
3748 if (*startBuf == '#') {
3749 // Skip whitespace.
3750 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3751 ;
3752 if (!strncmp(startBuf, "if", strlen("if")) ||
3753 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3754 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3755 !strncmp(startBuf, "define", strlen("define")) ||
3756 !strncmp(startBuf, "undef", strlen("undef")) ||
3757 !strncmp(startBuf, "else", strlen("else")) ||
3758 !strncmp(startBuf, "elif", strlen("elif")) ||
3759 !strncmp(startBuf, "endif", strlen("endif")) ||
3760 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3761 !strncmp(startBuf, "include", strlen("include")) ||
3762 !strncmp(startBuf, "import", strlen("import")) ||
3763 !strncmp(startBuf, "include_next", strlen("include_next")))
3764 return true;
3765 }
3766 startBuf++;
3767 }
3768 return false;
3769}
3770
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003771/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3772/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003773bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003774 TagDecl *Tag,
3775 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003776 if (!IDecl)
3777 return false;
3778 SourceLocation TagLocation;
3779 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3780 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003781 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003782 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003783 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003784 TagLocation = RD->getLocation();
3785 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003786 IDecl->getLocation(), TagLocation);
3787 }
3788 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3789 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3790 return false;
3791 IsNamedDefinition = true;
3792 TagLocation = ED->getLocation();
3793 return Context->getSourceManager().isBeforeInTranslationUnit(
3794 IDecl->getLocation(), TagLocation);
3795
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003796 }
3797 return false;
3798}
3799
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003800/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003801/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003802bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3803 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003804 if (isa<TypedefType>(Type)) {
3805 Result += "\t";
3806 return false;
3807 }
3808
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003809 if (Type->isArrayType()) {
3810 QualType ElemTy = Context->getBaseElementType(Type);
3811 return RewriteObjCFieldDeclType(ElemTy, Result);
3812 }
3813 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003814 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3815 if (RD->isCompleteDefinition()) {
3816 if (RD->isStruct())
3817 Result += "\n\tstruct ";
3818 else if (RD->isUnion())
3819 Result += "\n\tunion ";
3820 else
3821 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003822
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003823 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003824 if (GlobalDefinedTags.count(RD)) {
3825 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003826 Result += " ";
3827 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003828 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003829 Result += " {\n";
3830 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003831 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003832 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003833 RewriteObjCFieldDecl(FD, Result);
3834 }
3835 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003836 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003837 }
3838 }
3839 else if (Type->isEnumeralType()) {
3840 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3841 if (ED->isCompleteDefinition()) {
3842 Result += "\n\tenum ";
3843 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003844 if (GlobalDefinedTags.count(ED)) {
3845 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003846 Result += " ";
3847 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003848 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003849
3850 Result += " {\n";
3851 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3852 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3853 Result += "\t"; Result += EC->getName(); Result += " = ";
3854 llvm::APSInt Val = EC->getInitVal();
3855 Result += Val.toString(10);
3856 Result += ",\n";
3857 }
3858 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003859 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003860 }
3861 }
3862
3863 Result += "\t";
3864 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003865 return false;
3866}
3867
3868
3869/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3870/// It handles elaborated types, as well as enum types in the process.
3871void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3872 std::string &Result) {
3873 QualType Type = fieldDecl->getType();
3874 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003875
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003876 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3877 if (!EleboratedType)
3878 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003879 Result += Name;
3880 if (fieldDecl->isBitField()) {
3881 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3882 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003883 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003884 const ArrayType *AT = Context->getAsArrayType(Type);
3885 do {
3886 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003887 Result += "[";
3888 llvm::APInt Dim = CAT->getSize();
3889 Result += utostr(Dim.getZExtValue());
3890 Result += "]";
3891 }
Eli Friedman6febf122012-12-13 01:43:21 +00003892 AT = Context->getAsArrayType(AT->getElementType());
3893 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003894 }
3895
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003896 Result += ";\n";
3897}
3898
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003899/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3900/// named aggregate types into the input buffer.
3901void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3902 std::string &Result) {
3903 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003904 if (isa<TypedefType>(Type))
3905 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003906 if (Type->isArrayType())
3907 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003908 ObjCContainerDecl *IDecl =
3909 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003910
3911 TagDecl *TD = 0;
3912 if (Type->isRecordType()) {
3913 TD = Type->getAs<RecordType>()->getDecl();
3914 }
3915 else if (Type->isEnumeralType()) {
3916 TD = Type->getAs<EnumType>()->getDecl();
3917 }
3918
3919 if (TD) {
3920 if (GlobalDefinedTags.count(TD))
3921 return;
3922
3923 bool IsNamedDefinition = false;
3924 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3925 RewriteObjCFieldDeclType(Type, Result);
3926 Result += ";";
3927 }
3928 if (IsNamedDefinition)
3929 GlobalDefinedTags.insert(TD);
3930 }
3931
3932}
3933
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003934unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3935 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3936 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3937 return IvarGroupNumber[IV];
3938 }
3939 unsigned GroupNo = 0;
3940 SmallVector<const ObjCIvarDecl *, 8> IVars;
3941 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3942 IVD; IVD = IVD->getNextIvar())
3943 IVars.push_back(IVD);
3944
3945 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3946 if (IVars[i]->isBitField()) {
3947 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3948 while (i < e && IVars[i]->isBitField())
3949 IvarGroupNumber[IVars[i++]] = GroupNo;
3950 if (i < e)
3951 --i;
3952 }
3953
3954 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3955 return IvarGroupNumber[IV];
3956}
3957
3958QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3959 ObjCIvarDecl *IV,
3960 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3961 std::string StructTagName;
3962 ObjCIvarBitfieldGroupType(IV, StructTagName);
3963 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3964 Context->getTranslationUnitDecl(),
3965 SourceLocation(), SourceLocation(),
3966 &Context->Idents.get(StructTagName));
3967 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3968 ObjCIvarDecl *Ivar = IVars[i];
3969 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3970 &Context->Idents.get(Ivar->getName()),
3971 Ivar->getType(),
3972 0, /*Expr *BW */Ivar->getBitWidth(), false,
3973 ICIS_NoInit));
3974 }
3975 RD->completeDefinition();
3976 return Context->getTagDeclType(RD);
3977}
3978
3979QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3980 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3981 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3982 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3983 if (GroupRecordType.count(tuple))
3984 return GroupRecordType[tuple];
3985
3986 SmallVector<ObjCIvarDecl *, 8> IVars;
3987 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3988 IVD; IVD = IVD->getNextIvar()) {
3989 if (IVD->isBitField())
3990 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3991 else {
3992 if (!IVars.empty()) {
3993 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3994 // Generate the struct type for this group of bitfield ivars.
3995 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3996 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3997 IVars.clear();
3998 }
3999 }
4000 }
4001 if (!IVars.empty()) {
4002 // Do the last one.
4003 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
4004 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4005 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4006 }
4007 QualType RetQT = GroupRecordType[tuple];
4008 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4009
4010 return RetQT;
4011}
4012
4013/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4014/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4015void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4016 std::string &Result) {
4017 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4018 Result += CDecl->getName();
4019 Result += "__GRBF_";
4020 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4021 Result += utostr(GroupNo);
4022 return;
4023}
4024
4025/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4026/// Name of the struct would be: classname__T_n where n is the group number for
4027/// this ivar.
4028void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4029 std::string &Result) {
4030 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4031 Result += CDecl->getName();
4032 Result += "__T_";
4033 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4034 Result += utostr(GroupNo);
4035 return;
4036}
4037
4038/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4039/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4040/// this ivar.
4041void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4042 std::string &Result) {
4043 Result += "OBJC_IVAR_$_";
4044 ObjCIvarBitfieldGroupDecl(IV, Result);
4045}
4046
4047#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4048 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4049 ++IX; \
4050 if (IX < ENDIX) \
4051 --IX; \
4052}
4053
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4055/// an objective-c class with ivars.
4056void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4057 std::string &Result) {
4058 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4059 assert(CDecl->getName() != "" &&
4060 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004061 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004062 SmallVector<ObjCIvarDecl *, 8> IVars;
4063 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004064 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004065 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004066
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004067 SourceLocation LocStart = CDecl->getLocStart();
4068 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004069
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004070 const char *startBuf = SM->getCharacterData(LocStart);
4071 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004072
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004073 // If no ivars and no root or if its root, directly or indirectly,
4074 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004075 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004076 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4077 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4078 ReplaceText(LocStart, endBuf-startBuf, Result);
4079 return;
4080 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004081
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004082 // Insert named struct/union definitions inside class to
4083 // outer scope. This follows semantics of locally defined
4084 // struct/unions in objective-c classes.
4085 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4086 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004087
4088 // Insert named structs which are syntheized to group ivar bitfields
4089 // to outer scope as well.
4090 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4091 if (IVars[i]->isBitField()) {
4092 ObjCIvarDecl *IV = IVars[i];
4093 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4094 RewriteObjCFieldDeclType(QT, Result);
4095 Result += ";";
4096 // skip over ivar bitfields in this group.
4097 SKIP_BITFIELDS(i , e, IVars);
4098 }
4099
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004100 Result += "\nstruct ";
4101 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004102 Result += "_IMPL {\n";
4103
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004104 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004105 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4106 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4107 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004108 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004109
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004110 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4111 if (IVars[i]->isBitField()) {
4112 ObjCIvarDecl *IV = IVars[i];
4113 Result += "\tstruct ";
4114 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4115 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4116 // skip over ivar bitfields in this group.
4117 SKIP_BITFIELDS(i , e, IVars);
4118 }
4119 else
4120 RewriteObjCFieldDecl(IVars[i], Result);
4121 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004122
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004123 Result += "};\n";
4124 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4125 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004126 // Mark this struct as having been generated.
4127 if (!ObjCSynthesizedStructs.insert(CDecl))
4128 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004129}
4130
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004131/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4132/// have been referenced in an ivar access expression.
4133void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4134 std::string &Result) {
4135 // write out ivar offset symbols which have been referenced in an ivar
4136 // access expression.
4137 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4138 if (Ivars.empty())
4139 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004140
4141 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004142 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4143 e = Ivars.end(); i != e; i++) {
4144 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004145 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4146 unsigned GroupNo = 0;
4147 if (IvarDecl->isBitField()) {
4148 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4149 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4150 continue;
4151 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004152 Result += "\n";
4153 if (LangOpts.MicrosoftExt)
4154 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004155 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004156 if (LangOpts.MicrosoftExt &&
4157 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004158 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4159 Result += "__declspec(dllimport) ";
4160
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004161 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004162 if (IvarDecl->isBitField()) {
4163 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4164 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4165 }
4166 else
4167 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004168 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004169 }
4170}
4171
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004172//===----------------------------------------------------------------------===//
4173// Meta Data Emission
4174//===----------------------------------------------------------------------===//
4175
4176
4177/// RewriteImplementations - This routine rewrites all method implementations
4178/// and emits meta-data.
4179
4180void RewriteModernObjC::RewriteImplementations() {
4181 int ClsDefCount = ClassImplementation.size();
4182 int CatDefCount = CategoryImplementation.size();
4183
4184 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004185 for (int i = 0; i < ClsDefCount; i++) {
4186 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4187 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4188 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004189 assert(false &&
4190 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004191 RewriteImplementationDecl(OIMP);
4192 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004193
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004194 for (int i = 0; i < CatDefCount; i++) {
4195 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4196 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4197 if (CDecl->isImplicitInterfaceDecl())
4198 assert(false &&
4199 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004200 RewriteImplementationDecl(CIMP);
4201 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004202}
4203
4204void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4205 const std::string &Name,
4206 ValueDecl *VD, bool def) {
4207 assert(BlockByRefDeclNo.count(VD) &&
4208 "RewriteByRefString: ByRef decl missing");
4209 if (def)
4210 ResultStr += "struct ";
4211 ResultStr += "__Block_byref_" + Name +
4212 "_" + utostr(BlockByRefDeclNo[VD]) ;
4213}
4214
4215static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4216 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4217 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4218 return false;
4219}
4220
4221std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4222 StringRef funcName,
4223 std::string Tag) {
4224 const FunctionType *AFT = CE->getFunctionType();
4225 QualType RT = AFT->getResultType();
4226 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004227 SourceLocation BlockLoc = CE->getExprLoc();
4228 std::string S;
4229 ConvertSourceLocationToLineDirective(BlockLoc, S);
4230
4231 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4232 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004233
4234 BlockDecl *BD = CE->getBlockDecl();
4235
4236 if (isa<FunctionNoProtoType>(AFT)) {
4237 // No user-supplied arguments. Still need to pass in a pointer to the
4238 // block (to reference imported block decl refs).
4239 S += "(" + StructRef + " *__cself)";
4240 } else if (BD->param_empty()) {
4241 S += "(" + StructRef + " *__cself)";
4242 } else {
4243 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4244 assert(FT && "SynthesizeBlockFunc: No function proto");
4245 S += '(';
4246 // first add the implicit argument.
4247 S += StructRef + " *__cself, ";
4248 std::string ParamStr;
4249 for (BlockDecl::param_iterator AI = BD->param_begin(),
4250 E = BD->param_end(); AI != E; ++AI) {
4251 if (AI != BD->param_begin()) S += ", ";
4252 ParamStr = (*AI)->getNameAsString();
4253 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004254 (void)convertBlockPointerToFunctionPointer(QT);
4255 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004256 S += ParamStr;
4257 }
4258 if (FT->isVariadic()) {
4259 if (!BD->param_empty()) S += ", ";
4260 S += "...";
4261 }
4262 S += ')';
4263 }
4264 S += " {\n";
4265
4266 // Create local declarations to avoid rewriting all closure decl ref exprs.
4267 // First, emit a declaration for all "by ref" decls.
4268 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4269 E = BlockByRefDecls.end(); I != E; ++I) {
4270 S += " ";
4271 std::string Name = (*I)->getNameAsString();
4272 std::string TypeString;
4273 RewriteByRefString(TypeString, Name, (*I));
4274 TypeString += " *";
4275 Name = TypeString + Name;
4276 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4277 }
4278 // Next, emit a declaration for all "by copy" declarations.
4279 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4280 E = BlockByCopyDecls.end(); I != E; ++I) {
4281 S += " ";
4282 // Handle nested closure invocation. For example:
4283 //
4284 // void (^myImportedClosure)(void);
4285 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4286 //
4287 // void (^anotherClosure)(void);
4288 // anotherClosure = ^(void) {
4289 // myImportedClosure(); // import and invoke the closure
4290 // };
4291 //
4292 if (isTopLevelBlockPointerType((*I)->getType())) {
4293 RewriteBlockPointerTypeVariable(S, (*I));
4294 S += " = (";
4295 RewriteBlockPointerType(S, (*I)->getType());
4296 S += ")";
4297 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4298 }
4299 else {
4300 std::string Name = (*I)->getNameAsString();
4301 QualType QT = (*I)->getType();
4302 if (HasLocalVariableExternalStorage(*I))
4303 QT = Context->getPointerType(QT);
4304 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4305 S += Name + " = __cself->" +
4306 (*I)->getNameAsString() + "; // bound by copy\n";
4307 }
4308 }
4309 std::string RewrittenStr = RewrittenBlockExprs[CE];
4310 const char *cstr = RewrittenStr.c_str();
4311 while (*cstr++ != '{') ;
4312 S += cstr;
4313 S += "\n";
4314 return S;
4315}
4316
4317std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4318 StringRef funcName,
4319 std::string Tag) {
4320 std::string StructRef = "struct " + Tag;
4321 std::string S = "static void __";
4322
4323 S += funcName;
4324 S += "_block_copy_" + utostr(i);
4325 S += "(" + StructRef;
4326 S += "*dst, " + StructRef;
4327 S += "*src) {";
4328 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4329 E = ImportedBlockDecls.end(); I != E; ++I) {
4330 ValueDecl *VD = (*I);
4331 S += "_Block_object_assign((void*)&dst->";
4332 S += (*I)->getNameAsString();
4333 S += ", (void*)src->";
4334 S += (*I)->getNameAsString();
4335 if (BlockByRefDeclsPtrSet.count((*I)))
4336 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4337 else if (VD->getType()->isBlockPointerType())
4338 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4339 else
4340 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4341 }
4342 S += "}\n";
4343
4344 S += "\nstatic void __";
4345 S += funcName;
4346 S += "_block_dispose_" + utostr(i);
4347 S += "(" + StructRef;
4348 S += "*src) {";
4349 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4350 E = ImportedBlockDecls.end(); I != E; ++I) {
4351 ValueDecl *VD = (*I);
4352 S += "_Block_object_dispose((void*)src->";
4353 S += (*I)->getNameAsString();
4354 if (BlockByRefDeclsPtrSet.count((*I)))
4355 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4356 else if (VD->getType()->isBlockPointerType())
4357 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4358 else
4359 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4360 }
4361 S += "}\n";
4362 return S;
4363}
4364
4365std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4366 std::string Desc) {
4367 std::string S = "\nstruct " + Tag;
4368 std::string Constructor = " " + Tag;
4369
4370 S += " {\n struct __block_impl impl;\n";
4371 S += " struct " + Desc;
4372 S += "* Desc;\n";
4373
4374 Constructor += "(void *fp, "; // Invoke function pointer.
4375 Constructor += "struct " + Desc; // Descriptor pointer.
4376 Constructor += " *desc";
4377
4378 if (BlockDeclRefs.size()) {
4379 // Output all "by copy" declarations.
4380 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4381 E = BlockByCopyDecls.end(); I != E; ++I) {
4382 S += " ";
4383 std::string FieldName = (*I)->getNameAsString();
4384 std::string ArgName = "_" + FieldName;
4385 // Handle nested closure invocation. For example:
4386 //
4387 // void (^myImportedBlock)(void);
4388 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4389 //
4390 // void (^anotherBlock)(void);
4391 // anotherBlock = ^(void) {
4392 // myImportedBlock(); // import and invoke the closure
4393 // };
4394 //
4395 if (isTopLevelBlockPointerType((*I)->getType())) {
4396 S += "struct __block_impl *";
4397 Constructor += ", void *" + ArgName;
4398 } else {
4399 QualType QT = (*I)->getType();
4400 if (HasLocalVariableExternalStorage(*I))
4401 QT = Context->getPointerType(QT);
4402 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4403 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4404 Constructor += ", " + ArgName;
4405 }
4406 S += FieldName + ";\n";
4407 }
4408 // Output all "by ref" declarations.
4409 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4410 E = BlockByRefDecls.end(); I != E; ++I) {
4411 S += " ";
4412 std::string FieldName = (*I)->getNameAsString();
4413 std::string ArgName = "_" + FieldName;
4414 {
4415 std::string TypeString;
4416 RewriteByRefString(TypeString, FieldName, (*I));
4417 TypeString += " *";
4418 FieldName = TypeString + FieldName;
4419 ArgName = TypeString + ArgName;
4420 Constructor += ", " + ArgName;
4421 }
4422 S += FieldName + "; // by ref\n";
4423 }
4424 // Finish writing the constructor.
4425 Constructor += ", int flags=0)";
4426 // Initialize all "by copy" arguments.
4427 bool firsTime = true;
4428 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4429 E = BlockByCopyDecls.end(); I != E; ++I) {
4430 std::string Name = (*I)->getNameAsString();
4431 if (firsTime) {
4432 Constructor += " : ";
4433 firsTime = false;
4434 }
4435 else
4436 Constructor += ", ";
4437 if (isTopLevelBlockPointerType((*I)->getType()))
4438 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4439 else
4440 Constructor += Name + "(_" + Name + ")";
4441 }
4442 // Initialize all "by ref" arguments.
4443 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4444 E = BlockByRefDecls.end(); I != E; ++I) {
4445 std::string Name = (*I)->getNameAsString();
4446 if (firsTime) {
4447 Constructor += " : ";
4448 firsTime = false;
4449 }
4450 else
4451 Constructor += ", ";
4452 Constructor += Name + "(_" + Name + "->__forwarding)";
4453 }
4454
4455 Constructor += " {\n";
4456 if (GlobalVarDecl)
4457 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4458 else
4459 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4460 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4461
4462 Constructor += " Desc = desc;\n";
4463 } else {
4464 // Finish writing the constructor.
4465 Constructor += ", int flags=0) {\n";
4466 if (GlobalVarDecl)
4467 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4468 else
4469 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4470 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4471 Constructor += " Desc = desc;\n";
4472 }
4473 Constructor += " ";
4474 Constructor += "}\n";
4475 S += Constructor;
4476 S += "};\n";
4477 return S;
4478}
4479
4480std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4481 std::string ImplTag, int i,
4482 StringRef FunName,
4483 unsigned hasCopy) {
4484 std::string S = "\nstatic struct " + DescTag;
4485
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004486 S += " {\n size_t reserved;\n";
4487 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004488 if (hasCopy) {
4489 S += " void (*copy)(struct ";
4490 S += ImplTag; S += "*, struct ";
4491 S += ImplTag; S += "*);\n";
4492
4493 S += " void (*dispose)(struct ";
4494 S += ImplTag; S += "*);\n";
4495 }
4496 S += "} ";
4497
4498 S += DescTag + "_DATA = { 0, sizeof(struct ";
4499 S += ImplTag + ")";
4500 if (hasCopy) {
4501 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4502 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4503 }
4504 S += "};\n";
4505 return S;
4506}
4507
4508void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4509 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004510 bool RewriteSC = (GlobalVarDecl &&
4511 !Blocks.empty() &&
4512 GlobalVarDecl->getStorageClass() == SC_Static &&
4513 GlobalVarDecl->getType().getCVRQualifiers());
4514 if (RewriteSC) {
4515 std::string SC(" void __");
4516 SC += GlobalVarDecl->getNameAsString();
4517 SC += "() {}";
4518 InsertText(FunLocStart, SC);
4519 }
4520
4521 // Insert closures that were part of the function.
4522 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4523 CollectBlockDeclRefInfo(Blocks[i]);
4524 // Need to copy-in the inner copied-in variables not actually used in this
4525 // block.
4526 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004527 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004528 ValueDecl *VD = Exp->getDecl();
4529 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004530 if (!VD->hasAttr<BlocksAttr>()) {
4531 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4532 BlockByCopyDeclsPtrSet.insert(VD);
4533 BlockByCopyDecls.push_back(VD);
4534 }
4535 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004536 }
John McCallf4b88a42012-03-10 09:33:50 +00004537
4538 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004539 BlockByRefDeclsPtrSet.insert(VD);
4540 BlockByRefDecls.push_back(VD);
4541 }
John McCallf4b88a42012-03-10 09:33:50 +00004542
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004543 // imported objects in the inner blocks not used in the outer
4544 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004545 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004546 VD->getType()->isBlockPointerType())
4547 ImportedBlockDecls.insert(VD);
4548 }
4549
4550 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4551 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4552
4553 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4554
4555 InsertText(FunLocStart, CI);
4556
4557 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4558
4559 InsertText(FunLocStart, CF);
4560
4561 if (ImportedBlockDecls.size()) {
4562 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4563 InsertText(FunLocStart, HF);
4564 }
4565 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4566 ImportedBlockDecls.size() > 0);
4567 InsertText(FunLocStart, BD);
4568
4569 BlockDeclRefs.clear();
4570 BlockByRefDecls.clear();
4571 BlockByRefDeclsPtrSet.clear();
4572 BlockByCopyDecls.clear();
4573 BlockByCopyDeclsPtrSet.clear();
4574 ImportedBlockDecls.clear();
4575 }
4576 if (RewriteSC) {
4577 // Must insert any 'const/volatile/static here. Since it has been
4578 // removed as result of rewriting of block literals.
4579 std::string SC;
4580 if (GlobalVarDecl->getStorageClass() == SC_Static)
4581 SC = "static ";
4582 if (GlobalVarDecl->getType().isConstQualified())
4583 SC += "const ";
4584 if (GlobalVarDecl->getType().isVolatileQualified())
4585 SC += "volatile ";
4586 if (GlobalVarDecl->getType().isRestrictQualified())
4587 SC += "restrict ";
4588 InsertText(FunLocStart, SC);
4589 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004590 if (GlobalConstructionExp) {
4591 // extra fancy dance for global literal expression.
4592
4593 // Always the latest block expression on the block stack.
4594 std::string Tag = "__";
4595 Tag += FunName;
4596 Tag += "_block_impl_";
4597 Tag += utostr(Blocks.size()-1);
4598 std::string globalBuf = "static ";
4599 globalBuf += Tag; globalBuf += " ";
4600 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004601
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004602 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004603 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004604 PrintingPolicy(LangOpts));
4605 globalBuf += constructorExprBuf.str();
4606 globalBuf += ";\n";
4607 InsertText(FunLocStart, globalBuf);
4608 GlobalConstructionExp = 0;
4609 }
4610
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004611 Blocks.clear();
4612 InnerDeclRefsCount.clear();
4613 InnerDeclRefs.clear();
4614 RewrittenBlockExprs.clear();
4615}
4616
4617void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004618 SourceLocation FunLocStart =
4619 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4620 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004621 StringRef FuncName = FD->getName();
4622
4623 SynthesizeBlockLiterals(FunLocStart, FuncName);
4624}
4625
4626static void BuildUniqueMethodName(std::string &Name,
4627 ObjCMethodDecl *MD) {
4628 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4629 Name = IFace->getName();
4630 Name += "__" + MD->getSelector().getAsString();
4631 // Convert colons to underscores.
4632 std::string::size_type loc = 0;
4633 while ((loc = Name.find(":", loc)) != std::string::npos)
4634 Name.replace(loc, 1, "_");
4635}
4636
4637void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4638 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4639 //SourceLocation FunLocStart = MD->getLocStart();
4640 SourceLocation FunLocStart = MD->getLocStart();
4641 std::string FuncName;
4642 BuildUniqueMethodName(FuncName, MD);
4643 SynthesizeBlockLiterals(FunLocStart, FuncName);
4644}
4645
4646void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4647 for (Stmt::child_range CI = S->children(); CI; ++CI)
4648 if (*CI) {
4649 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4650 GetBlockDeclRefExprs(CBE->getBody());
4651 else
4652 GetBlockDeclRefExprs(*CI);
4653 }
4654 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004655 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4656 if (DRE->refersToEnclosingLocal()) {
4657 // FIXME: Handle enums.
4658 if (!isa<FunctionDecl>(DRE->getDecl()))
4659 BlockDeclRefs.push_back(DRE);
4660 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4661 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004662 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004663 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004664
4665 return;
4666}
4667
4668void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004669 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004670 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4671 for (Stmt::child_range CI = S->children(); CI; ++CI)
4672 if (*CI) {
4673 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4674 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4675 GetInnerBlockDeclRefExprs(CBE->getBody(),
4676 InnerBlockDeclRefs,
4677 InnerContexts);
4678 }
4679 else
4680 GetInnerBlockDeclRefExprs(*CI,
4681 InnerBlockDeclRefs,
4682 InnerContexts);
4683
4684 }
4685 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004686 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4687 if (DRE->refersToEnclosingLocal()) {
4688 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4689 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4690 InnerBlockDeclRefs.push_back(DRE);
4691 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4692 if (Var->isFunctionOrMethodVarDecl())
4693 ImportedLocalExternalDecls.insert(Var);
4694 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004695 }
4696
4697 return;
4698}
4699
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004700/// convertObjCTypeToCStyleType - This routine converts such objc types
4701/// as qualified objects, and blocks to their closest c/c++ types that
4702/// it can. It returns true if input type was modified.
4703bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4704 QualType oldT = T;
4705 convertBlockPointerToFunctionPointer(T);
4706 if (T->isFunctionPointerType()) {
4707 QualType PointeeTy;
4708 if (const PointerType* PT = T->getAs<PointerType>()) {
4709 PointeeTy = PT->getPointeeType();
4710 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4711 T = convertFunctionTypeOfBlocks(FT);
4712 T = Context->getPointerType(T);
4713 }
4714 }
4715 }
4716
4717 convertToUnqualifiedObjCType(T);
4718 return T != oldT;
4719}
4720
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004721/// convertFunctionTypeOfBlocks - This routine converts a function type
4722/// whose result type may be a block pointer or whose argument type(s)
4723/// might be block pointers to an equivalent function type replacing
4724/// all block pointers to function pointers.
4725QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4726 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4727 // FTP will be null for closures that don't take arguments.
4728 // Generate a funky cast.
4729 SmallVector<QualType, 8> ArgTypes;
4730 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004731 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004732
4733 if (FTP) {
4734 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4735 E = FTP->arg_type_end(); I && (I != E); ++I) {
4736 QualType t = *I;
4737 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004738 if (convertObjCTypeToCStyleType(t))
4739 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004740 ArgTypes.push_back(t);
4741 }
4742 }
4743 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004744 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004745 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4746 else FuncType = QualType(FT, 0);
4747 return FuncType;
4748}
4749
4750Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4751 // Navigate to relevant type information.
4752 const BlockPointerType *CPT = 0;
4753
4754 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4755 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004756 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4757 CPT = MExpr->getType()->getAs<BlockPointerType>();
4758 }
4759 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4760 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4761 }
4762 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4763 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4764 else if (const ConditionalOperator *CEXPR =
4765 dyn_cast<ConditionalOperator>(BlockExp)) {
4766 Expr *LHSExp = CEXPR->getLHS();
4767 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4768 Expr *RHSExp = CEXPR->getRHS();
4769 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4770 Expr *CONDExp = CEXPR->getCond();
4771 ConditionalOperator *CondExpr =
4772 new (Context) ConditionalOperator(CONDExp,
4773 SourceLocation(), cast<Expr>(LHSStmt),
4774 SourceLocation(), cast<Expr>(RHSStmt),
4775 Exp->getType(), VK_RValue, OK_Ordinary);
4776 return CondExpr;
4777 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4778 CPT = IRE->getType()->getAs<BlockPointerType>();
4779 } else if (const PseudoObjectExpr *POE
4780 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4781 CPT = POE->getType()->castAs<BlockPointerType>();
4782 } else {
4783 assert(1 && "RewriteBlockClass: Bad type");
4784 }
4785 assert(CPT && "RewriteBlockClass: Bad type");
4786 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4787 assert(FT && "RewriteBlockClass: Bad type");
4788 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4789 // FTP will be null for closures that don't take arguments.
4790
4791 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4792 SourceLocation(), SourceLocation(),
4793 &Context->Idents.get("__block_impl"));
4794 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4795
4796 // Generate a funky cast.
4797 SmallVector<QualType, 8> ArgTypes;
4798
4799 // Push the block argument type.
4800 ArgTypes.push_back(PtrBlock);
4801 if (FTP) {
4802 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4803 E = FTP->arg_type_end(); I && (I != E); ++I) {
4804 QualType t = *I;
4805 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4806 if (!convertBlockPointerToFunctionPointer(t))
4807 convertToUnqualifiedObjCType(t);
4808 ArgTypes.push_back(t);
4809 }
4810 }
4811 // Now do the pointer to function cast.
4812 QualType PtrToFuncCastType
4813 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4814
4815 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4816
4817 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4818 CK_BitCast,
4819 const_cast<Expr*>(BlockExp));
4820 // Don't forget the parens to enforce the proper binding.
4821 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4822 BlkCast);
4823 //PE->dump();
4824
4825 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4826 SourceLocation(),
4827 &Context->Idents.get("FuncPtr"),
4828 Context->VoidPtrTy, 0,
4829 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004830 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004831 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4832 FD->getType(), VK_LValue,
4833 OK_Ordinary);
4834
4835
4836 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4837 CK_BitCast, ME);
4838 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4839
4840 SmallVector<Expr*, 8> BlkExprs;
4841 // Add the implicit argument.
4842 BlkExprs.push_back(BlkCast);
4843 // Add the user arguments.
4844 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4845 E = Exp->arg_end(); I != E; ++I) {
4846 BlkExprs.push_back(*I);
4847 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004848 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004849 Exp->getType(), VK_RValue,
4850 SourceLocation());
4851 return CE;
4852}
4853
4854// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004855// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004856// For example:
4857//
4858// int main() {
4859// __block Foo *f;
4860// __block int i;
4861//
4862// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004863// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004864// i = 77;
4865// };
4866//}
John McCallf4b88a42012-03-10 09:33:50 +00004867Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004868 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4869 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004870 ValueDecl *VD = DeclRefExp->getDecl();
4871 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004872
4873 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4874 SourceLocation(),
4875 &Context->Idents.get("__forwarding"),
4876 Context->VoidPtrTy, 0,
4877 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004878 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004879 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4880 FD, SourceLocation(),
4881 FD->getType(), VK_LValue,
4882 OK_Ordinary);
4883
4884 StringRef Name = VD->getName();
4885 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4886 &Context->Idents.get(Name),
4887 Context->VoidPtrTy, 0,
4888 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004889 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004890 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4891 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4892
4893
4894
4895 // Need parens to enforce precedence.
4896 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4897 DeclRefExp->getExprLoc(),
4898 ME);
4899 ReplaceStmt(DeclRefExp, PE);
4900 return PE;
4901}
4902
4903// Rewrites the imported local variable V with external storage
4904// (static, extern, etc.) as *V
4905//
4906Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4907 ValueDecl *VD = DRE->getDecl();
4908 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4909 if (!ImportedLocalExternalDecls.count(Var))
4910 return DRE;
4911 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4912 VK_LValue, OK_Ordinary,
4913 DRE->getLocation());
4914 // Need parens to enforce precedence.
4915 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4916 Exp);
4917 ReplaceStmt(DRE, PE);
4918 return PE;
4919}
4920
4921void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4922 SourceLocation LocStart = CE->getLParenLoc();
4923 SourceLocation LocEnd = CE->getRParenLoc();
4924
4925 // Need to avoid trying to rewrite synthesized casts.
4926 if (LocStart.isInvalid())
4927 return;
4928 // Need to avoid trying to rewrite casts contained in macros.
4929 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4930 return;
4931
4932 const char *startBuf = SM->getCharacterData(LocStart);
4933 const char *endBuf = SM->getCharacterData(LocEnd);
4934 QualType QT = CE->getType();
4935 const Type* TypePtr = QT->getAs<Type>();
4936 if (isa<TypeOfExprType>(TypePtr)) {
4937 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4938 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4939 std::string TypeAsString = "(";
4940 RewriteBlockPointerType(TypeAsString, QT);
4941 TypeAsString += ")";
4942 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4943 return;
4944 }
4945 // advance the location to startArgList.
4946 const char *argPtr = startBuf;
4947
4948 while (*argPtr++ && (argPtr < endBuf)) {
4949 switch (*argPtr) {
4950 case '^':
4951 // Replace the '^' with '*'.
4952 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4953 ReplaceText(LocStart, 1, "*");
4954 break;
4955 }
4956 }
4957 return;
4958}
4959
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004960void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4961 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004962 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4963 CastKind != CK_AnyPointerToBlockPointerCast)
4964 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004965
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004966 QualType QT = IC->getType();
4967 (void)convertBlockPointerToFunctionPointer(QT);
4968 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4969 std::string Str = "(";
4970 Str += TypeString;
4971 Str += ")";
4972 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4973
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004974 return;
4975}
4976
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004977void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4978 SourceLocation DeclLoc = FD->getLocation();
4979 unsigned parenCount = 0;
4980
4981 // We have 1 or more arguments that have closure pointers.
4982 const char *startBuf = SM->getCharacterData(DeclLoc);
4983 const char *startArgList = strchr(startBuf, '(');
4984
4985 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4986
4987 parenCount++;
4988 // advance the location to startArgList.
4989 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4990 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4991
4992 const char *argPtr = startArgList;
4993
4994 while (*argPtr++ && parenCount) {
4995 switch (*argPtr) {
4996 case '^':
4997 // Replace the '^' with '*'.
4998 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4999 ReplaceText(DeclLoc, 1, "*");
5000 break;
5001 case '(':
5002 parenCount++;
5003 break;
5004 case ')':
5005 parenCount--;
5006 break;
5007 }
5008 }
5009 return;
5010}
5011
5012bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5013 const FunctionProtoType *FTP;
5014 const PointerType *PT = QT->getAs<PointerType>();
5015 if (PT) {
5016 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5017 } else {
5018 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5019 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5020 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5021 }
5022 if (FTP) {
5023 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5024 E = FTP->arg_type_end(); I != E; ++I)
5025 if (isTopLevelBlockPointerType(*I))
5026 return true;
5027 }
5028 return false;
5029}
5030
5031bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5032 const FunctionProtoType *FTP;
5033 const PointerType *PT = QT->getAs<PointerType>();
5034 if (PT) {
5035 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5036 } else {
5037 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5038 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5039 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5040 }
5041 if (FTP) {
5042 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5043 E = FTP->arg_type_end(); I != E; ++I) {
5044 if ((*I)->isObjCQualifiedIdType())
5045 return true;
5046 if ((*I)->isObjCObjectPointerType() &&
5047 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5048 return true;
5049 }
5050
5051 }
5052 return false;
5053}
5054
5055void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5056 const char *&RParen) {
5057 const char *argPtr = strchr(Name, '(');
5058 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5059
5060 LParen = argPtr; // output the start.
5061 argPtr++; // skip past the left paren.
5062 unsigned parenCount = 1;
5063
5064 while (*argPtr && parenCount) {
5065 switch (*argPtr) {
5066 case '(': parenCount++; break;
5067 case ')': parenCount--; break;
5068 default: break;
5069 }
5070 if (parenCount) argPtr++;
5071 }
5072 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5073 RParen = argPtr; // output the end
5074}
5075
5076void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5078 RewriteBlockPointerFunctionArgs(FD);
5079 return;
5080 }
5081 // Handle Variables and Typedefs.
5082 SourceLocation DeclLoc = ND->getLocation();
5083 QualType DeclT;
5084 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5085 DeclT = VD->getType();
5086 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5087 DeclT = TDD->getUnderlyingType();
5088 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5089 DeclT = FD->getType();
5090 else
5091 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5092
5093 const char *startBuf = SM->getCharacterData(DeclLoc);
5094 const char *endBuf = startBuf;
5095 // scan backward (from the decl location) for the end of the previous decl.
5096 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5097 startBuf--;
5098 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5099 std::string buf;
5100 unsigned OrigLength=0;
5101 // *startBuf != '^' if we are dealing with a pointer to function that
5102 // may take block argument types (which will be handled below).
5103 if (*startBuf == '^') {
5104 // Replace the '^' with '*', computing a negative offset.
5105 buf = '*';
5106 startBuf++;
5107 OrigLength++;
5108 }
5109 while (*startBuf != ')') {
5110 buf += *startBuf;
5111 startBuf++;
5112 OrigLength++;
5113 }
5114 buf += ')';
5115 OrigLength++;
5116
5117 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5118 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5119 // Replace the '^' with '*' for arguments.
5120 // Replace id<P> with id/*<>*/
5121 DeclLoc = ND->getLocation();
5122 startBuf = SM->getCharacterData(DeclLoc);
5123 const char *argListBegin, *argListEnd;
5124 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5125 while (argListBegin < argListEnd) {
5126 if (*argListBegin == '^')
5127 buf += '*';
5128 else if (*argListBegin == '<') {
5129 buf += "/*";
5130 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005131 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005132 while (*argListBegin != '>') {
5133 buf += *argListBegin++;
5134 OrigLength++;
5135 }
5136 buf += *argListBegin;
5137 buf += "*/";
5138 }
5139 else
5140 buf += *argListBegin;
5141 argListBegin++;
5142 OrigLength++;
5143 }
5144 buf += ')';
5145 OrigLength++;
5146 }
5147 ReplaceText(Start, OrigLength, buf);
5148
5149 return;
5150}
5151
5152
5153/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5154/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5155/// struct Block_byref_id_object *src) {
5156/// _Block_object_assign (&_dest->object, _src->object,
5157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5158/// [|BLOCK_FIELD_IS_WEAK]) // object
5159/// _Block_object_assign(&_dest->object, _src->object,
5160/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5161/// [|BLOCK_FIELD_IS_WEAK]) // block
5162/// }
5163/// And:
5164/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5165/// _Block_object_dispose(_src->object,
5166/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5167/// [|BLOCK_FIELD_IS_WEAK]) // object
5168/// _Block_object_dispose(_src->object,
5169/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5170/// [|BLOCK_FIELD_IS_WEAK]) // block
5171/// }
5172
5173std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5174 int flag) {
5175 std::string S;
5176 if (CopyDestroyCache.count(flag))
5177 return S;
5178 CopyDestroyCache.insert(flag);
5179 S = "static void __Block_byref_id_object_copy_";
5180 S += utostr(flag);
5181 S += "(void *dst, void *src) {\n";
5182
5183 // offset into the object pointer is computed as:
5184 // void * + void* + int + int + void* + void *
5185 unsigned IntSize =
5186 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5187 unsigned VoidPtrSize =
5188 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5189
5190 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5191 S += " _Block_object_assign((char*)dst + ";
5192 S += utostr(offset);
5193 S += ", *(void * *) ((char*)src + ";
5194 S += utostr(offset);
5195 S += "), ";
5196 S += utostr(flag);
5197 S += ");\n}\n";
5198
5199 S += "static void __Block_byref_id_object_dispose_";
5200 S += utostr(flag);
5201 S += "(void *src) {\n";
5202 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5203 S += utostr(offset);
5204 S += "), ";
5205 S += utostr(flag);
5206 S += ");\n}\n";
5207 return S;
5208}
5209
5210/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5211/// the declaration into:
5212/// struct __Block_byref_ND {
5213/// void *__isa; // NULL for everything except __weak pointers
5214/// struct __Block_byref_ND *__forwarding;
5215/// int32_t __flags;
5216/// int32_t __size;
5217/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5218/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5219/// typex ND;
5220/// };
5221///
5222/// It then replaces declaration of ND variable with:
5223/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5224/// __size=sizeof(struct __Block_byref_ND),
5225/// ND=initializer-if-any};
5226///
5227///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005228void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5229 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005230 int flag = 0;
5231 int isa = 0;
5232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5233 if (DeclLoc.isInvalid())
5234 // If type location is missing, it is because of missing type (a warning).
5235 // Use variable's location which is good for this case.
5236 DeclLoc = ND->getLocation();
5237 const char *startBuf = SM->getCharacterData(DeclLoc);
5238 SourceLocation X = ND->getLocEnd();
5239 X = SM->getExpansionLoc(X);
5240 const char *endBuf = SM->getCharacterData(X);
5241 std::string Name(ND->getNameAsString());
5242 std::string ByrefType;
5243 RewriteByRefString(ByrefType, Name, ND, true);
5244 ByrefType += " {\n";
5245 ByrefType += " void *__isa;\n";
5246 RewriteByRefString(ByrefType, Name, ND);
5247 ByrefType += " *__forwarding;\n";
5248 ByrefType += " int __flags;\n";
5249 ByrefType += " int __size;\n";
5250 // Add void *__Block_byref_id_object_copy;
5251 // void *__Block_byref_id_object_dispose; if needed.
5252 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005253 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005254 if (HasCopyAndDispose) {
5255 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5256 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5257 }
5258
5259 QualType T = Ty;
5260 (void)convertBlockPointerToFunctionPointer(T);
5261 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5262
5263 ByrefType += " " + Name + ";\n";
5264 ByrefType += "};\n";
5265 // Insert this type in global scope. It is needed by helper function.
5266 SourceLocation FunLocStart;
5267 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005268 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005269 else {
5270 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5271 FunLocStart = CurMethodDef->getLocStart();
5272 }
5273 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005274
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005275 if (Ty.isObjCGCWeak()) {
5276 flag |= BLOCK_FIELD_IS_WEAK;
5277 isa = 1;
5278 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005279 if (HasCopyAndDispose) {
5280 flag = BLOCK_BYREF_CALLER;
5281 QualType Ty = ND->getType();
5282 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5283 if (Ty->isBlockPointerType())
5284 flag |= BLOCK_FIELD_IS_BLOCK;
5285 else
5286 flag |= BLOCK_FIELD_IS_OBJECT;
5287 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5288 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005289 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005290 }
5291
5292 // struct __Block_byref_ND ND =
5293 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5294 // initializer-if-any};
5295 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005296 // FIXME. rewriter does not support __block c++ objects which
5297 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005298 if (hasInit)
5299 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5300 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5301 if (CXXDecl && CXXDecl->isDefaultConstructor())
5302 hasInit = false;
5303 }
5304
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005305 unsigned flags = 0;
5306 if (HasCopyAndDispose)
5307 flags |= BLOCK_HAS_COPY_DISPOSE;
5308 Name = ND->getNameAsString();
5309 ByrefType.clear();
5310 RewriteByRefString(ByrefType, Name, ND);
5311 std::string ForwardingCastType("(");
5312 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005313 ByrefType += " " + Name + " = {(void*)";
5314 ByrefType += utostr(isa);
5315 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5316 ByrefType += utostr(flags);
5317 ByrefType += ", ";
5318 ByrefType += "sizeof(";
5319 RewriteByRefString(ByrefType, Name, ND);
5320 ByrefType += ")";
5321 if (HasCopyAndDispose) {
5322 ByrefType += ", __Block_byref_id_object_copy_";
5323 ByrefType += utostr(flag);
5324 ByrefType += ", __Block_byref_id_object_dispose_";
5325 ByrefType += utostr(flag);
5326 }
5327
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005328 if (!firstDecl) {
5329 // In multiple __block declarations, and for all but 1st declaration,
5330 // find location of the separating comma. This would be start location
5331 // where new text is to be inserted.
5332 DeclLoc = ND->getLocation();
5333 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5334 const char *commaBuf = startDeclBuf;
5335 while (*commaBuf != ',')
5336 commaBuf--;
5337 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5338 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5339 startBuf = commaBuf;
5340 }
5341
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005342 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005343 ByrefType += "};\n";
5344 unsigned nameSize = Name.size();
5345 // for block or function pointer declaration. Name is aleady
5346 // part of the declaration.
5347 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5348 nameSize = 1;
5349 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5350 }
5351 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005352 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005353 SourceLocation startLoc;
5354 Expr *E = ND->getInit();
5355 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5356 startLoc = ECE->getLParenLoc();
5357 else
5358 startLoc = E->getLocStart();
5359 startLoc = SM->getExpansionLoc(startLoc);
5360 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005361 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005362
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005363 const char separator = lastDecl ? ';' : ',';
5364 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5365 const char *separatorBuf = strchr(startInitializerBuf, separator);
5366 assert((*separatorBuf == separator) &&
5367 "RewriteByRefVar: can't find ';' or ','");
5368 SourceLocation separatorLoc =
5369 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5370
5371 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005372 }
5373 return;
5374}
5375
5376void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5377 // Add initializers for any closure decl refs.
5378 GetBlockDeclRefExprs(Exp->getBody());
5379 if (BlockDeclRefs.size()) {
5380 // Unique all "by copy" declarations.
5381 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005382 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005383 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5384 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5385 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5386 }
5387 }
5388 // Unique all "by ref" declarations.
5389 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005390 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005391 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5392 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5393 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5394 }
5395 }
5396 // Find any imported blocks...they will need special attention.
5397 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005398 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005399 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5400 BlockDeclRefs[i]->getType()->isBlockPointerType())
5401 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5402 }
5403}
5404
5405FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5406 IdentifierInfo *ID = &Context->Idents.get(name);
5407 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5408 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5409 SourceLocation(), ID, FType, 0, SC_Extern,
5410 SC_None, false, false);
5411}
5412
5413Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005414 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005415
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005416 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005417
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005418 Blocks.push_back(Exp);
5419
5420 CollectBlockDeclRefInfo(Exp);
5421
5422 // Add inner imported variables now used in current block.
5423 int countOfInnerDecls = 0;
5424 if (!InnerBlockDeclRefs.empty()) {
5425 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005426 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005427 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005428 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005429 // We need to save the copied-in variables in nested
5430 // blocks because it is needed at the end for some of the API generations.
5431 // See SynthesizeBlockLiterals routine.
5432 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5433 BlockDeclRefs.push_back(Exp);
5434 BlockByCopyDeclsPtrSet.insert(VD);
5435 BlockByCopyDecls.push_back(VD);
5436 }
John McCallf4b88a42012-03-10 09:33:50 +00005437 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005438 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5439 BlockDeclRefs.push_back(Exp);
5440 BlockByRefDeclsPtrSet.insert(VD);
5441 BlockByRefDecls.push_back(VD);
5442 }
5443 }
5444 // Find any imported blocks...they will need special attention.
5445 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005446 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005447 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5448 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5449 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5450 }
5451 InnerDeclRefsCount.push_back(countOfInnerDecls);
5452
5453 std::string FuncName;
5454
5455 if (CurFunctionDef)
5456 FuncName = CurFunctionDef->getNameAsString();
5457 else if (CurMethodDef)
5458 BuildUniqueMethodName(FuncName, CurMethodDef);
5459 else if (GlobalVarDecl)
5460 FuncName = std::string(GlobalVarDecl->getNameAsString());
5461
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005462 bool GlobalBlockExpr =
5463 block->getDeclContext()->getRedeclContext()->isFileContext();
5464
5465 if (GlobalBlockExpr && !GlobalVarDecl) {
5466 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5467 GlobalBlockExpr = false;
5468 }
5469
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005470 std::string BlockNumber = utostr(Blocks.size()-1);
5471
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005472 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5473
5474 // Get a pointer to the function type so we can cast appropriately.
5475 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5476 QualType FType = Context->getPointerType(BFT);
5477
5478 FunctionDecl *FD;
5479 Expr *NewRep;
5480
5481 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005482 std::string Tag;
5483
5484 if (GlobalBlockExpr)
5485 Tag = "__global_";
5486 else
5487 Tag = "__";
5488 Tag += FuncName + "_block_impl_" + BlockNumber;
5489
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005490 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005491 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005492 SourceLocation());
5493
5494 SmallVector<Expr*, 4> InitExprs;
5495
5496 // Initialize the block function.
5497 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005498 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5499 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005500 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5501 CK_BitCast, Arg);
5502 InitExprs.push_back(castExpr);
5503
5504 // Initialize the block descriptor.
5505 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5506
5507 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5508 SourceLocation(), SourceLocation(),
5509 &Context->Idents.get(DescData.c_str()),
5510 Context->VoidPtrTy, 0,
5511 SC_Static, SC_None);
5512 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005513 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005514 Context->VoidPtrTy,
5515 VK_LValue,
5516 SourceLocation()),
5517 UO_AddrOf,
5518 Context->getPointerType(Context->VoidPtrTy),
5519 VK_RValue, OK_Ordinary,
5520 SourceLocation());
5521 InitExprs.push_back(DescRefExpr);
5522
5523 // Add initializers for any closure decl refs.
5524 if (BlockDeclRefs.size()) {
5525 Expr *Exp;
5526 // Output all "by copy" declarations.
5527 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5528 E = BlockByCopyDecls.end(); I != E; ++I) {
5529 if (isObjCType((*I)->getType())) {
5530 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5531 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005532 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5533 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005534 if (HasLocalVariableExternalStorage(*I)) {
5535 QualType QT = (*I)->getType();
5536 QT = Context->getPointerType(QT);
5537 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5538 OK_Ordinary, SourceLocation());
5539 }
5540 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5541 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005542 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5543 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005544 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5545 CK_BitCast, Arg);
5546 } else {
5547 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005548 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5549 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005550 if (HasLocalVariableExternalStorage(*I)) {
5551 QualType QT = (*I)->getType();
5552 QT = Context->getPointerType(QT);
5553 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5554 OK_Ordinary, SourceLocation());
5555 }
5556
5557 }
5558 InitExprs.push_back(Exp);
5559 }
5560 // Output all "by ref" declarations.
5561 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5562 E = BlockByRefDecls.end(); I != E; ++I) {
5563 ValueDecl *ND = (*I);
5564 std::string Name(ND->getNameAsString());
5565 std::string RecName;
5566 RewriteByRefString(RecName, Name, ND, true);
5567 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5568 + sizeof("struct"));
5569 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5570 SourceLocation(), SourceLocation(),
5571 II);
5572 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5573 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5574
5575 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005576 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005577 SourceLocation());
5578 bool isNestedCapturedVar = false;
5579 if (block)
5580 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5581 ce = block->capture_end(); ci != ce; ++ci) {
5582 const VarDecl *variable = ci->getVariable();
5583 if (variable == ND && ci->isNested()) {
5584 assert (ci->isByRef() &&
5585 "SynthBlockInitExpr - captured block variable is not byref");
5586 isNestedCapturedVar = true;
5587 break;
5588 }
5589 }
5590 // captured nested byref variable has its address passed. Do not take
5591 // its address again.
5592 if (!isNestedCapturedVar)
5593 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5594 Context->getPointerType(Exp->getType()),
5595 VK_RValue, OK_Ordinary, SourceLocation());
5596 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5597 InitExprs.push_back(Exp);
5598 }
5599 }
5600 if (ImportedBlockDecls.size()) {
5601 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5602 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5603 unsigned IntSize =
5604 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5605 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5606 Context->IntTy, SourceLocation());
5607 InitExprs.push_back(FlagExp);
5608 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005609 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005610 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005611
5612 if (GlobalBlockExpr) {
5613 assert (GlobalConstructionExp == 0 &&
5614 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5615 GlobalConstructionExp = NewRep;
5616 NewRep = DRE;
5617 }
5618
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005619 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5620 Context->getPointerType(NewRep->getType()),
5621 VK_RValue, OK_Ordinary, SourceLocation());
5622 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5623 NewRep);
5624 BlockDeclRefs.clear();
5625 BlockByRefDecls.clear();
5626 BlockByRefDeclsPtrSet.clear();
5627 BlockByCopyDecls.clear();
5628 BlockByCopyDeclsPtrSet.clear();
5629 ImportedBlockDecls.clear();
5630 return NewRep;
5631}
5632
5633bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5634 if (const ObjCForCollectionStmt * CS =
5635 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5636 return CS->getElement() == DS;
5637 return false;
5638}
5639
5640//===----------------------------------------------------------------------===//
5641// Function Body / Expression rewriting
5642//===----------------------------------------------------------------------===//
5643
5644Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5645 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5646 isa<DoStmt>(S) || isa<ForStmt>(S))
5647 Stmts.push_back(S);
5648 else if (isa<ObjCForCollectionStmt>(S)) {
5649 Stmts.push_back(S);
5650 ObjCBcLabelNo.push_back(++BcLabelCount);
5651 }
5652
5653 // Pseudo-object operations and ivar references need special
5654 // treatment because we're going to recursively rewrite them.
5655 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5656 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5657 return RewritePropertyOrImplicitSetter(PseudoOp);
5658 } else {
5659 return RewritePropertyOrImplicitGetter(PseudoOp);
5660 }
5661 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5662 return RewriteObjCIvarRefExpr(IvarRefExpr);
5663 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005664 else if (isa<OpaqueValueExpr>(S))
5665 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005666
5667 SourceRange OrigStmtRange = S->getSourceRange();
5668
5669 // Perform a bottom up rewrite of all children.
5670 for (Stmt::child_range CI = S->children(); CI; ++CI)
5671 if (*CI) {
5672 Stmt *childStmt = (*CI);
5673 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5674 if (newStmt) {
5675 *CI = newStmt;
5676 }
5677 }
5678
5679 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005680 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005681 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5682 InnerContexts.insert(BE->getBlockDecl());
5683 ImportedLocalExternalDecls.clear();
5684 GetInnerBlockDeclRefExprs(BE->getBody(),
5685 InnerBlockDeclRefs, InnerContexts);
5686 // Rewrite the block body in place.
5687 Stmt *SaveCurrentBody = CurrentBody;
5688 CurrentBody = BE->getBody();
5689 PropParentMap = 0;
5690 // block literal on rhs of a property-dot-sytax assignment
5691 // must be replaced by its synthesize ast so getRewrittenText
5692 // works as expected. In this case, what actually ends up on RHS
5693 // is the blockTranscribed which is the helper function for the
5694 // block literal; as in: self.c = ^() {[ace ARR];};
5695 bool saveDisableReplaceStmt = DisableReplaceStmt;
5696 DisableReplaceStmt = false;
5697 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5698 DisableReplaceStmt = saveDisableReplaceStmt;
5699 CurrentBody = SaveCurrentBody;
5700 PropParentMap = 0;
5701 ImportedLocalExternalDecls.clear();
5702 // Now we snarf the rewritten text and stash it away for later use.
5703 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5704 RewrittenBlockExprs[BE] = Str;
5705
5706 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5707
5708 //blockTranscribed->dump();
5709 ReplaceStmt(S, blockTranscribed);
5710 return blockTranscribed;
5711 }
5712 // Handle specific things.
5713 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5714 return RewriteAtEncode(AtEncode);
5715
5716 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5717 return RewriteAtSelector(AtSelector);
5718
5719 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5720 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005721
5722 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5723 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005724
Patrick Beardeb382ec2012-04-19 00:25:12 +00005725 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5726 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005727
5728 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5729 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005730
5731 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5732 dyn_cast<ObjCDictionaryLiteral>(S))
5733 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005734
5735 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5736#if 0
5737 // Before we rewrite it, put the original message expression in a comment.
5738 SourceLocation startLoc = MessExpr->getLocStart();
5739 SourceLocation endLoc = MessExpr->getLocEnd();
5740
5741 const char *startBuf = SM->getCharacterData(startLoc);
5742 const char *endBuf = SM->getCharacterData(endLoc);
5743
5744 std::string messString;
5745 messString += "// ";
5746 messString.append(startBuf, endBuf-startBuf+1);
5747 messString += "\n";
5748
5749 // FIXME: Missing definition of
5750 // InsertText(clang::SourceLocation, char const*, unsigned int).
5751 // InsertText(startLoc, messString.c_str(), messString.size());
5752 // Tried this, but it didn't work either...
5753 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5754#endif
5755 return RewriteMessageExpr(MessExpr);
5756 }
5757
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005758 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5759 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5760 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5761 }
5762
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005763 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5764 return RewriteObjCTryStmt(StmtTry);
5765
5766 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5767 return RewriteObjCSynchronizedStmt(StmtTry);
5768
5769 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5770 return RewriteObjCThrowStmt(StmtThrow);
5771
5772 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5773 return RewriteObjCProtocolExpr(ProtocolExp);
5774
5775 if (ObjCForCollectionStmt *StmtForCollection =
5776 dyn_cast<ObjCForCollectionStmt>(S))
5777 return RewriteObjCForCollectionStmt(StmtForCollection,
5778 OrigStmtRange.getEnd());
5779 if (BreakStmt *StmtBreakStmt =
5780 dyn_cast<BreakStmt>(S))
5781 return RewriteBreakStmt(StmtBreakStmt);
5782 if (ContinueStmt *StmtContinueStmt =
5783 dyn_cast<ContinueStmt>(S))
5784 return RewriteContinueStmt(StmtContinueStmt);
5785
5786 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5787 // and cast exprs.
5788 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5789 // FIXME: What we're doing here is modifying the type-specifier that
5790 // precedes the first Decl. In the future the DeclGroup should have
5791 // a separate type-specifier that we can rewrite.
5792 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5793 // the context of an ObjCForCollectionStmt. For example:
5794 // NSArray *someArray;
5795 // for (id <FooProtocol> index in someArray) ;
5796 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5797 // and it depends on the original text locations/positions.
5798 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5799 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5800
5801 // Blocks rewrite rules.
5802 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5803 DI != DE; ++DI) {
5804 Decl *SD = *DI;
5805 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5806 if (isTopLevelBlockPointerType(ND->getType()))
5807 RewriteBlockPointerDecl(ND);
5808 else if (ND->getType()->isFunctionPointerType())
5809 CheckFunctionPointerDecl(ND->getType(), ND);
5810 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5811 if (VD->hasAttr<BlocksAttr>()) {
5812 static unsigned uniqueByrefDeclCount = 0;
5813 assert(!BlockByRefDeclNo.count(ND) &&
5814 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5815 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005816 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005817 }
5818 else
5819 RewriteTypeOfDecl(VD);
5820 }
5821 }
5822 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5823 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5824 RewriteBlockPointerDecl(TD);
5825 else if (TD->getUnderlyingType()->isFunctionPointerType())
5826 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5827 }
5828 }
5829 }
5830
5831 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5832 RewriteObjCQualifiedInterfaceTypes(CE);
5833
5834 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5835 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5836 assert(!Stmts.empty() && "Statement stack is empty");
5837 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5838 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5839 && "Statement stack mismatch");
5840 Stmts.pop_back();
5841 }
5842 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005843 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5844 ValueDecl *VD = DRE->getDecl();
5845 if (VD->hasAttr<BlocksAttr>())
5846 return RewriteBlockDeclRefExpr(DRE);
5847 if (HasLocalVariableExternalStorage(VD))
5848 return RewriteLocalVariableExternalStorage(DRE);
5849 }
5850
5851 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5852 if (CE->getCallee()->getType()->isBlockPointerType()) {
5853 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5854 ReplaceStmt(S, BlockCall);
5855 return BlockCall;
5856 }
5857 }
5858 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5859 RewriteCastExpr(CE);
5860 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005861 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5862 RewriteImplicitCastObjCExpr(ICE);
5863 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005864#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005865
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005866 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5867 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5868 ICE->getSubExpr(),
5869 SourceLocation());
5870 // Get the new text.
5871 std::string SStr;
5872 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005873 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005874 const std::string &Str = Buf.str();
5875
5876 printf("CAST = %s\n", &Str[0]);
5877 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5878 delete S;
5879 return Replacement;
5880 }
5881#endif
5882 // Return this stmt unmodified.
5883 return S;
5884}
5885
5886void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5887 for (RecordDecl::field_iterator i = RD->field_begin(),
5888 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005889 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005890 if (isTopLevelBlockPointerType(FD->getType()))
5891 RewriteBlockPointerDecl(FD);
5892 if (FD->getType()->isObjCQualifiedIdType() ||
5893 FD->getType()->isObjCQualifiedInterfaceType())
5894 RewriteObjCQualifiedInterfaceTypes(FD);
5895 }
5896}
5897
5898/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5899/// main file of the input.
5900void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5901 switch (D->getKind()) {
5902 case Decl::Function: {
5903 FunctionDecl *FD = cast<FunctionDecl>(D);
5904 if (FD->isOverloadedOperator())
5905 return;
5906
5907 // Since function prototypes don't have ParmDecl's, we check the function
5908 // prototype. This enables us to rewrite function declarations and
5909 // definitions using the same code.
5910 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5911
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005912 if (!FD->isThisDeclarationADefinition())
5913 break;
5914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005915 // FIXME: If this should support Obj-C++, support CXXTryStmt
5916 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5917 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005918 CurrentBody = Body;
5919 Body =
5920 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5921 FD->setBody(Body);
5922 CurrentBody = 0;
5923 if (PropParentMap) {
5924 delete PropParentMap;
5925 PropParentMap = 0;
5926 }
5927 // This synthesizes and inserts the block "impl" struct, invoke function,
5928 // and any copy/dispose helper functions.
5929 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005930 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005931 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005932 }
5933 break;
5934 }
5935 case Decl::ObjCMethod: {
5936 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5937 if (CompoundStmt *Body = MD->getCompoundBody()) {
5938 CurMethodDef = MD;
5939 CurrentBody = Body;
5940 Body =
5941 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5942 MD->setBody(Body);
5943 CurrentBody = 0;
5944 if (PropParentMap) {
5945 delete PropParentMap;
5946 PropParentMap = 0;
5947 }
5948 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005949 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005950 CurMethodDef = 0;
5951 }
5952 break;
5953 }
5954 case Decl::ObjCImplementation: {
5955 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5956 ClassImplementation.push_back(CI);
5957 break;
5958 }
5959 case Decl::ObjCCategoryImpl: {
5960 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5961 CategoryImplementation.push_back(CI);
5962 break;
5963 }
5964 case Decl::Var: {
5965 VarDecl *VD = cast<VarDecl>(D);
5966 RewriteObjCQualifiedInterfaceTypes(VD);
5967 if (isTopLevelBlockPointerType(VD->getType()))
5968 RewriteBlockPointerDecl(VD);
5969 else if (VD->getType()->isFunctionPointerType()) {
5970 CheckFunctionPointerDecl(VD->getType(), VD);
5971 if (VD->getInit()) {
5972 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5973 RewriteCastExpr(CE);
5974 }
5975 }
5976 } else if (VD->getType()->isRecordType()) {
5977 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5978 if (RD->isCompleteDefinition())
5979 RewriteRecordBody(RD);
5980 }
5981 if (VD->getInit()) {
5982 GlobalVarDecl = VD;
5983 CurrentBody = VD->getInit();
5984 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5985 CurrentBody = 0;
5986 if (PropParentMap) {
5987 delete PropParentMap;
5988 PropParentMap = 0;
5989 }
5990 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5991 GlobalVarDecl = 0;
5992
5993 // This is needed for blocks.
5994 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5995 RewriteCastExpr(CE);
5996 }
5997 }
5998 break;
5999 }
6000 case Decl::TypeAlias:
6001 case Decl::Typedef: {
6002 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6003 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
6004 RewriteBlockPointerDecl(TD);
6005 else if (TD->getUnderlyingType()->isFunctionPointerType())
6006 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6007 }
6008 break;
6009 }
6010 case Decl::CXXRecord:
6011 case Decl::Record: {
6012 RecordDecl *RD = cast<RecordDecl>(D);
6013 if (RD->isCompleteDefinition())
6014 RewriteRecordBody(RD);
6015 break;
6016 }
6017 default:
6018 break;
6019 }
6020 // Nothing yet.
6021}
6022
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006023/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6024/// protocol reference symbols in the for of:
6025/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6026static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6027 ObjCProtocolDecl *PDecl,
6028 std::string &Result) {
6029 // Also output .objc_protorefs$B section and its meta-data.
6030 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006031 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006032 Result += "struct _protocol_t *";
6033 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6034 Result += PDecl->getNameAsString();
6035 Result += " = &";
6036 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6037 Result += ";\n";
6038}
6039
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006040void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6041 if (Diags.hasErrorOccurred())
6042 return;
6043
6044 RewriteInclude();
6045
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006046 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6047 // translation of function bodies were postponed untill all class and
6048 // their extensions and implementations are seen. This is because, we
6049 // cannot build grouping structs for bitfields untill they are all seen.
6050 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6051 HandleTopLevelSingleDecl(FDecl);
6052 }
6053
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006054 // Here's a great place to add any extra declarations that may be needed.
6055 // Write out meta data for each @protocol(<expr>).
6056 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006057 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006058 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006059 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6060 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006061
6062 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006063
6064 if (ClassImplementation.size() || CategoryImplementation.size())
6065 RewriteImplementations();
6066
Fariborz Jahanian57317782012-02-21 23:58:41 +00006067 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6068 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6069 // Write struct declaration for the class matching its ivar declarations.
6070 // Note that for modern abi, this is postponed until the end of TU
6071 // because class extensions and the implementation might declare their own
6072 // private ivars.
6073 RewriteInterfaceDecl(CDecl);
6074 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006075
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006076 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6077 // we are done.
6078 if (const RewriteBuffer *RewriteBuf =
6079 Rewrite.getRewriteBufferFor(MainFileID)) {
6080 //printf("Changed:\n");
6081 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6082 } else {
6083 llvm::errs() << "No changes\n";
6084 }
6085
6086 if (ClassImplementation.size() || CategoryImplementation.size() ||
6087 ProtocolExprDecls.size()) {
6088 // Rewrite Objective-c meta data*
6089 std::string ResultStr;
6090 RewriteMetaDataIntoBuffer(ResultStr);
6091 // Emit metadata.
6092 *OutFile << ResultStr;
6093 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006094 // Emit ImageInfo;
6095 {
6096 std::string ResultStr;
6097 WriteImageInfo(ResultStr);
6098 *OutFile << ResultStr;
6099 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006100 OutFile->flush();
6101}
6102
6103void RewriteModernObjC::Initialize(ASTContext &context) {
6104 InitializeCommon(context);
6105
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006106 Preamble += "#ifndef __OBJC2__\n";
6107 Preamble += "#define __OBJC2__\n";
6108 Preamble += "#endif\n";
6109
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006110 // declaring objc_selector outside the parameter list removes a silly
6111 // scope related warning...
6112 if (IsHeader)
6113 Preamble = "#pragma once\n";
6114 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006115 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6116 Preamble += "\n\tstruct objc_object *superClass; ";
6117 // Add a constructor for creating temporary objects.
6118 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6119 Preamble += ": object(o), superClass(s) {} ";
6120 Preamble += "\n};\n";
6121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006122 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006123 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006124 // These are currently generated.
6125 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006126 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006127 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006128 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6129 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006130 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006131 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006132 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6133 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006134 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006135
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006136 // These need be generated for performance. Currently they are not,
6137 // using API calls instead.
6138 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6139 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6140 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6141
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006142 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006143 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6144 Preamble += "typedef struct objc_object Protocol;\n";
6145 Preamble += "#define _REWRITER_typedef_Protocol\n";
6146 Preamble += "#endif\n";
6147 if (LangOpts.MicrosoftExt) {
6148 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6149 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006150 }
6151 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006152 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006153
6154 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6155 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6156 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6157 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6158 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6159
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006160 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006161 Preamble += "(const char *);\n";
6162 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6163 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006164 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006165 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006166 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006167 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006168 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6169 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006170 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6171 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6172 Preamble += "struct __objcFastEnumerationState {\n\t";
6173 Preamble += "unsigned long state;\n\t";
6174 Preamble += "void **itemsPtr;\n\t";
6175 Preamble += "unsigned long *mutationsPtr;\n\t";
6176 Preamble += "unsigned long extra[5];\n};\n";
6177 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6178 Preamble += "#define __FASTENUMERATIONSTATE\n";
6179 Preamble += "#endif\n";
6180 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6181 Preamble += "struct __NSConstantStringImpl {\n";
6182 Preamble += " int *isa;\n";
6183 Preamble += " int flags;\n";
6184 Preamble += " char *str;\n";
6185 Preamble += " long length;\n";
6186 Preamble += "};\n";
6187 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6188 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6189 Preamble += "#else\n";
6190 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6191 Preamble += "#endif\n";
6192 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6193 Preamble += "#endif\n";
6194 // Blocks preamble.
6195 Preamble += "#ifndef BLOCK_IMPL\n";
6196 Preamble += "#define BLOCK_IMPL\n";
6197 Preamble += "struct __block_impl {\n";
6198 Preamble += " void *isa;\n";
6199 Preamble += " int Flags;\n";
6200 Preamble += " int Reserved;\n";
6201 Preamble += " void *FuncPtr;\n";
6202 Preamble += "};\n";
6203 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6204 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6205 Preamble += "extern \"C\" __declspec(dllexport) "
6206 "void _Block_object_assign(void *, const void *, const int);\n";
6207 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6208 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6209 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6210 Preamble += "#else\n";
6211 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6212 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6213 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6214 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6215 Preamble += "#endif\n";
6216 Preamble += "#endif\n";
6217 if (LangOpts.MicrosoftExt) {
6218 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6219 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6220 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6221 Preamble += "#define __attribute__(X)\n";
6222 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006223 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006224 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006225 Preamble += "#endif\n";
6226 Preamble += "#ifndef __block\n";
6227 Preamble += "#define __block\n";
6228 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006229 }
6230 else {
6231 Preamble += "#define __block\n";
6232 Preamble += "#define __weak\n";
6233 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006234
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006235 // Declarations required for modern objective-c array and dictionary literals.
6236 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006237 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006238 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006239 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006240 Preamble += "\tva_list marker;\n";
6241 Preamble += "\tva_start(marker, count);\n";
6242 Preamble += "\tarr = new void *[count];\n";
6243 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6244 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6245 Preamble += "\tva_end( marker );\n";
6246 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006247 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006248 Preamble += "\tdelete[] arr;\n";
6249 Preamble += " }\n";
6250 Preamble += "};\n";
6251
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006252 // Declaration required for implementation of @autoreleasepool statement.
6253 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6254 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6255 Preamble += "struct __AtAutoreleasePool {\n";
6256 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6257 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6258 Preamble += " void * atautoreleasepoolobj;\n";
6259 Preamble += "};\n";
6260
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006261 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6262 // as this avoids warning in any 64bit/32bit compilation model.
6263 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6264}
6265
6266/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6267/// ivar offset.
6268void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6269 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006270 Result += "__OFFSETOFIVAR__(struct ";
6271 Result += ivar->getContainingInterface()->getNameAsString();
6272 if (LangOpts.MicrosoftExt)
6273 Result += "_IMPL";
6274 Result += ", ";
6275 if (ivar->isBitField())
6276 ObjCIvarBitfieldGroupDecl(ivar, Result);
6277 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006278 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006279 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006280}
6281
6282/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6283/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006284/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006285/// char *attributes;
6286/// }
6287
6288/// struct _prop_list_t {
6289/// uint32_t entsize; // sizeof(struct _prop_t)
6290/// uint32_t count_of_properties;
6291/// struct _prop_t prop_list[count_of_properties];
6292/// }
6293
6294/// struct _protocol_t;
6295
6296/// struct _protocol_list_t {
6297/// long protocol_count; // Note, this is 32/64 bit
6298/// struct _protocol_t * protocol_list[protocol_count];
6299/// }
6300
6301/// struct _objc_method {
6302/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006303/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006304/// char *_imp;
6305/// }
6306
6307/// struct _method_list_t {
6308/// uint32_t entsize; // sizeof(struct _objc_method)
6309/// uint32_t method_count;
6310/// struct _objc_method method_list[method_count];
6311/// }
6312
6313/// struct _protocol_t {
6314/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006315/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006316/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006317/// const struct method_list_t *instance_methods;
6318/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006319/// const struct method_list_t *optionalInstanceMethods;
6320/// const struct method_list_t *optionalClassMethods;
6321/// const struct _prop_list_t * properties;
6322/// const uint32_t size; // sizeof(struct _protocol_t)
6323/// const uint32_t flags; // = 0
6324/// const char ** extendedMethodTypes;
6325/// }
6326
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006327/// struct _ivar_t {
6328/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006329/// const char *name;
6330/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006331/// uint32_t alignment;
6332/// uint32_t size;
6333/// }
6334
6335/// struct _ivar_list_t {
6336/// uint32 entsize; // sizeof(struct _ivar_t)
6337/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006338/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006339/// }
6340
6341/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006342/// uint32_t flags;
6343/// uint32_t instanceStart;
6344/// uint32_t instanceSize;
6345/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006346/// const uint8_t *ivarLayout;
6347/// const char *name;
6348/// const struct _method_list_t *baseMethods;
6349/// const struct _protocol_list_t *baseProtocols;
6350/// const struct _ivar_list_t *ivars;
6351/// const uint8_t *weakIvarLayout;
6352/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006353/// }
6354
6355/// struct _class_t {
6356/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006357/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006358/// void *cache;
6359/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006360/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006361/// }
6362
6363/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006364/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006365/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006366/// const struct _method_list_t *instance_methods;
6367/// const struct _method_list_t *class_methods;
6368/// const struct _protocol_list_t *protocols;
6369/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006370/// }
6371
6372/// MessageRefTy - LLVM for:
6373/// struct _message_ref_t {
6374/// IMP messenger;
6375/// SEL name;
6376/// };
6377
6378/// SuperMessageRefTy - LLVM for:
6379/// struct _super_message_ref_t {
6380/// SUPER_IMP messenger;
6381/// SEL name;
6382/// };
6383
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006384static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006385 static bool meta_data_declared = false;
6386 if (meta_data_declared)
6387 return;
6388
6389 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006390 Result += "\tconst char *name;\n";
6391 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392 Result += "};\n";
6393
6394 Result += "\nstruct _protocol_t;\n";
6395
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006396 Result += "\nstruct _objc_method {\n";
6397 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006398 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006399 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006400 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006401
6402 Result += "\nstruct _protocol_t {\n";
6403 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006404 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006405 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006406 Result += "\tconst struct method_list_t *instance_methods;\n";
6407 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006408 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6409 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6410 Result += "\tconst struct _prop_list_t * properties;\n";
6411 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6412 Result += "\tconst unsigned int flags; // = 0\n";
6413 Result += "\tconst char ** extendedMethodTypes;\n";
6414 Result += "};\n";
6415
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006416 Result += "\nstruct _ivar_t {\n";
6417 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006418 Result += "\tconst char *name;\n";
6419 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006420 Result += "\tunsigned int alignment;\n";
6421 Result += "\tunsigned int size;\n";
6422 Result += "};\n";
6423
6424 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006425 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006426 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006427 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006428 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6429 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006430 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006431 Result += "\tconst unsigned char *ivarLayout;\n";
6432 Result += "\tconst char *name;\n";
6433 Result += "\tconst struct _method_list_t *baseMethods;\n";
6434 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6435 Result += "\tconst struct _ivar_list_t *ivars;\n";
6436 Result += "\tconst unsigned char *weakIvarLayout;\n";
6437 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006438 Result += "};\n";
6439
6440 Result += "\nstruct _class_t {\n";
6441 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006442 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006443 Result += "\tvoid *cache;\n";
6444 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006445 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006446 Result += "};\n";
6447
6448 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006449 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006450 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006451 Result += "\tconst struct _method_list_t *instance_methods;\n";
6452 Result += "\tconst struct _method_list_t *class_methods;\n";
6453 Result += "\tconst struct _protocol_list_t *protocols;\n";
6454 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006455 Result += "};\n";
6456
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006457 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006458 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006459 meta_data_declared = true;
6460}
6461
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006462static void Write_protocol_list_t_TypeDecl(std::string &Result,
6463 long super_protocol_count) {
6464 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6465 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6466 Result += "\tstruct _protocol_t *super_protocols[";
6467 Result += utostr(super_protocol_count); Result += "];\n";
6468 Result += "}";
6469}
6470
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006471static void Write_method_list_t_TypeDecl(std::string &Result,
6472 unsigned int method_count) {
6473 Result += "struct /*_method_list_t*/"; Result += " {\n";
6474 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6475 Result += "\tunsigned int method_count;\n";
6476 Result += "\tstruct _objc_method method_list[";
6477 Result += utostr(method_count); Result += "];\n";
6478 Result += "}";
6479}
6480
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006481static void Write__prop_list_t_TypeDecl(std::string &Result,
6482 unsigned int property_count) {
6483 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6484 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6485 Result += "\tunsigned int count_of_properties;\n";
6486 Result += "\tstruct _prop_t prop_list[";
6487 Result += utostr(property_count); Result += "];\n";
6488 Result += "}";
6489}
6490
Fariborz Jahanianae932952012-02-10 20:47:10 +00006491static void Write__ivar_list_t_TypeDecl(std::string &Result,
6492 unsigned int ivar_count) {
6493 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6494 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6495 Result += "\tunsigned int count;\n";
6496 Result += "\tstruct _ivar_t ivar_list[";
6497 Result += utostr(ivar_count); Result += "];\n";
6498 Result += "}";
6499}
6500
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006501static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6502 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6503 StringRef VarName,
6504 StringRef ProtocolName) {
6505 if (SuperProtocols.size() > 0) {
6506 Result += "\nstatic ";
6507 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6508 Result += " "; Result += VarName;
6509 Result += ProtocolName;
6510 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6511 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6512 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6513 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6514 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6515 Result += SuperPD->getNameAsString();
6516 if (i == e-1)
6517 Result += "\n};\n";
6518 else
6519 Result += ",\n";
6520 }
6521 }
6522}
6523
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006524static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6525 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006526 ArrayRef<ObjCMethodDecl *> Methods,
6527 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006528 StringRef TopLevelDeclName,
6529 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006530 if (Methods.size() > 0) {
6531 Result += "\nstatic ";
6532 Write_method_list_t_TypeDecl(Result, Methods.size());
6533 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006534 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006535 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6536 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6537 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6538 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6539 ObjCMethodDecl *MD = Methods[i];
6540 if (i == 0)
6541 Result += "\t{{(struct objc_selector *)\"";
6542 else
6543 Result += "\t{(struct objc_selector *)\"";
6544 Result += (MD)->getSelector().getAsString(); Result += "\"";
6545 Result += ", ";
6546 std::string MethodTypeString;
6547 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6548 Result += "\""; Result += MethodTypeString; Result += "\"";
6549 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006550 if (!MethodImpl)
6551 Result += "0";
6552 else {
6553 Result += "(void *)";
6554 Result += RewriteObj.MethodInternalNames[MD];
6555 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006556 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006557 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006558 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006559 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006560 }
6561 Result += "};\n";
6562 }
6563}
6564
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006565static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006566 ASTContext *Context, std::string &Result,
6567 ArrayRef<ObjCPropertyDecl *> Properties,
6568 const Decl *Container,
6569 StringRef VarName,
6570 StringRef ProtocolName) {
6571 if (Properties.size() > 0) {
6572 Result += "\nstatic ";
6573 Write__prop_list_t_TypeDecl(Result, Properties.size());
6574 Result += " "; Result += VarName;
6575 Result += ProtocolName;
6576 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6577 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6578 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6579 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6580 ObjCPropertyDecl *PropDecl = Properties[i];
6581 if (i == 0)
6582 Result += "\t{{\"";
6583 else
6584 Result += "\t{\"";
6585 Result += PropDecl->getName(); Result += "\",";
6586 std::string PropertyTypeString, QuotePropertyTypeString;
6587 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6588 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6589 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6590 if (i == e-1)
6591 Result += "}}\n";
6592 else
6593 Result += "},\n";
6594 }
6595 Result += "};\n";
6596 }
6597}
6598
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006599// Metadata flags
6600enum MetaDataDlags {
6601 CLS = 0x0,
6602 CLS_META = 0x1,
6603 CLS_ROOT = 0x2,
6604 OBJC2_CLS_HIDDEN = 0x10,
6605 CLS_EXCEPTION = 0x20,
6606
6607 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6608 CLS_HAS_IVAR_RELEASER = 0x40,
6609 /// class was compiled with -fobjc-arr
6610 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6611};
6612
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006613static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6614 unsigned int flags,
6615 const std::string &InstanceStart,
6616 const std::string &InstanceSize,
6617 ArrayRef<ObjCMethodDecl *>baseMethods,
6618 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6619 ArrayRef<ObjCIvarDecl *>ivars,
6620 ArrayRef<ObjCPropertyDecl *>Properties,
6621 StringRef VarName,
6622 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006623 Result += "\nstatic struct _class_ro_t ";
6624 Result += VarName; Result += ClassName;
6625 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6626 Result += "\t";
6627 Result += llvm::utostr(flags); Result += ", ";
6628 Result += InstanceStart; Result += ", ";
6629 Result += InstanceSize; Result += ", \n";
6630 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006631 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6632 if (Triple.getArch() == llvm::Triple::x86_64)
6633 // uint32_t const reserved; // only when building for 64bit targets
6634 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006635 // const uint8_t * const ivarLayout;
6636 Result += "0, \n\t";
6637 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006638 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006639 if (baseMethods.size() > 0) {
6640 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006641 if (metaclass)
6642 Result += "_OBJC_$_CLASS_METHODS_";
6643 else
6644 Result += "_OBJC_$_INSTANCE_METHODS_";
6645 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006646 Result += ",\n\t";
6647 }
6648 else
6649 Result += "0, \n\t";
6650
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006651 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006652 Result += "(const struct _objc_protocol_list *)&";
6653 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6654 Result += ",\n\t";
6655 }
6656 else
6657 Result += "0, \n\t";
6658
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006659 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006660 Result += "(const struct _ivar_list_t *)&";
6661 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6662 Result += ",\n\t";
6663 }
6664 else
6665 Result += "0, \n\t";
6666
6667 // weakIvarLayout
6668 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006669 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006670 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006671 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006672 Result += ",\n";
6673 }
6674 else
6675 Result += "0, \n";
6676
6677 Result += "};\n";
6678}
6679
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006680static void Write_class_t(ASTContext *Context, std::string &Result,
6681 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006682 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6683 bool rootClass = (!CDecl->getSuperClass());
6684 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006685
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006686 if (!rootClass) {
6687 // Find the Root class
6688 RootClass = CDecl->getSuperClass();
6689 while (RootClass->getSuperClass()) {
6690 RootClass = RootClass->getSuperClass();
6691 }
6692 }
6693
6694 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006695 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006696 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006697 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006698 if (CDecl->getImplementation())
6699 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006700 else
6701 Result += "__declspec(dllimport) ";
6702
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006703 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006704 Result += CDecl->getNameAsString();
6705 Result += ";\n";
6706 }
6707 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006708 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006709 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006710 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006711 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006712 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006713 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006714 else
6715 Result += "__declspec(dllimport) ";
6716
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006717 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006718 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006719 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006720 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006721
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006722 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006723 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006724 if (RootClass->getImplementation())
6725 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006726 else
6727 Result += "__declspec(dllimport) ";
6728
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006729 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006730 Result += VarName;
6731 Result += RootClass->getNameAsString();
6732 Result += ";\n";
6733 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006734 }
6735
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006736 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6737 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006738 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6739 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006740 if (metaclass) {
6741 if (!rootClass) {
6742 Result += "0, // &"; Result += VarName;
6743 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006744 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006745 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006746 Result += CDecl->getSuperClass()->getNameAsString();
6747 Result += ",\n\t";
6748 }
6749 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006750 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006751 Result += CDecl->getNameAsString();
6752 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006753 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006754 Result += ",\n\t";
6755 }
6756 }
6757 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006758 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006759 Result += CDecl->getNameAsString();
6760 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006761 if (!rootClass) {
6762 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006763 Result += CDecl->getSuperClass()->getNameAsString();
6764 Result += ",\n\t";
6765 }
6766 else
6767 Result += "0,\n\t";
6768 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006769 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6770 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6771 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006772 Result += "&_OBJC_METACLASS_RO_$_";
6773 else
6774 Result += "&_OBJC_CLASS_RO_$_";
6775 Result += CDecl->getNameAsString();
6776 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006777
6778 // Add static function to initialize some of the meta-data fields.
6779 // avoid doing it twice.
6780 if (metaclass)
6781 return;
6782
6783 const ObjCInterfaceDecl *SuperClass =
6784 rootClass ? CDecl : CDecl->getSuperClass();
6785
6786 Result += "static void OBJC_CLASS_SETUP_$_";
6787 Result += CDecl->getNameAsString();
6788 Result += "(void ) {\n";
6789 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6790 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006791 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006792
6793 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006794 Result += ".superclass = ";
6795 if (rootClass)
6796 Result += "&OBJC_CLASS_$_";
6797 else
6798 Result += "&OBJC_METACLASS_$_";
6799
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006800 Result += SuperClass->getNameAsString(); Result += ";\n";
6801
6802 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6803 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6804
6805 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6806 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6807 Result += CDecl->getNameAsString(); Result += ";\n";
6808
6809 if (!rootClass) {
6810 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6811 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6812 Result += SuperClass->getNameAsString(); Result += ";\n";
6813 }
6814
6815 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6816 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6817 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006818}
6819
Fariborz Jahanian61186122012-02-17 18:40:41 +00006820static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6821 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006822 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006823 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006824 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6825 ArrayRef<ObjCMethodDecl *> ClassMethods,
6826 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6827 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006828 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006829 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006830 // must declare an extern class object in case this class is not implemented
6831 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006832 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006833 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006834 if (ClassDecl->getImplementation())
6835 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006836 else
6837 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006838
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006839 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006840 Result += "OBJC_CLASS_$_"; Result += ClassName;
6841 Result += ";\n";
6842
Fariborz Jahanian61186122012-02-17 18:40:41 +00006843 Result += "\nstatic struct _category_t ";
6844 Result += "_OBJC_$_CATEGORY_";
6845 Result += ClassName; Result += "_$_"; Result += CatName;
6846 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6847 Result += "{\n";
6848 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006849 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006850 Result += ",\n";
6851 if (InstanceMethods.size() > 0) {
6852 Result += "\t(const struct _method_list_t *)&";
6853 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6854 Result += ClassName; Result += "_$_"; Result += CatName;
6855 Result += ",\n";
6856 }
6857 else
6858 Result += "\t0,\n";
6859
6860 if (ClassMethods.size() > 0) {
6861 Result += "\t(const struct _method_list_t *)&";
6862 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6863 Result += ClassName; Result += "_$_"; Result += CatName;
6864 Result += ",\n";
6865 }
6866 else
6867 Result += "\t0,\n";
6868
6869 if (RefedProtocols.size() > 0) {
6870 Result += "\t(const struct _protocol_list_t *)&";
6871 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6872 Result += ClassName; Result += "_$_"; Result += CatName;
6873 Result += ",\n";
6874 }
6875 else
6876 Result += "\t0,\n";
6877
6878 if (ClassProperties.size() > 0) {
6879 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6880 Result += ClassName; Result += "_$_"; Result += CatName;
6881 Result += ",\n";
6882 }
6883 else
6884 Result += "\t0,\n";
6885
6886 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006887
6888 // Add static function to initialize the class pointer in the category structure.
6889 Result += "static void OBJC_CATEGORY_SETUP_$_";
6890 Result += ClassDecl->getNameAsString();
6891 Result += "_$_";
6892 Result += CatName;
6893 Result += "(void ) {\n";
6894 Result += "\t_OBJC_$_CATEGORY_";
6895 Result += ClassDecl->getNameAsString();
6896 Result += "_$_";
6897 Result += CatName;
6898 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6899 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006900}
6901
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006902static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6903 ASTContext *Context, std::string &Result,
6904 ArrayRef<ObjCMethodDecl *> Methods,
6905 StringRef VarName,
6906 StringRef ProtocolName) {
6907 if (Methods.size() == 0)
6908 return;
6909
6910 Result += "\nstatic const char *";
6911 Result += VarName; Result += ProtocolName;
6912 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6913 Result += "{\n";
6914 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6915 ObjCMethodDecl *MD = Methods[i];
6916 std::string MethodTypeString, QuoteMethodTypeString;
6917 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6918 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6919 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6920 if (i == e-1)
6921 Result += "\n};\n";
6922 else {
6923 Result += ",\n";
6924 }
6925 }
6926}
6927
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006928static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6929 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006930 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006931 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006932 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006933 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6934 // this is what happens:
6935 /**
6936 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6937 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6938 Class->getVisibility() == HiddenVisibility)
6939 Visibility shoud be: HiddenVisibility;
6940 else
6941 Visibility shoud be: DefaultVisibility;
6942 */
6943
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006944 Result += "\n";
6945 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6946 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006947 if (Context->getLangOpts().MicrosoftExt)
6948 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6949
6950 if (!Context->getLangOpts().MicrosoftExt ||
6951 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006952 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006953 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006954 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006955 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006956 if (Ivars[i]->isBitField())
6957 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6958 else
6959 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006960 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6961 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006962 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6963 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006964 if (Ivars[i]->isBitField()) {
6965 // skip over rest of the ivar bitfields.
6966 SKIP_BITFIELDS(i , e, Ivars);
6967 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006968 }
6969}
6970
Fariborz Jahanianae932952012-02-10 20:47:10 +00006971static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6972 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006973 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006974 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006975 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006976 if (OriginalIvars.size() > 0) {
6977 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6978 SmallVector<ObjCIvarDecl *, 8> Ivars;
6979 // strip off all but the first ivar bitfield from each group of ivars.
6980 // Such ivars in the ivar list table will be replaced by their grouping struct
6981 // 'ivar'.
6982 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6983 if (OriginalIvars[i]->isBitField()) {
6984 Ivars.push_back(OriginalIvars[i]);
6985 // skip over rest of the ivar bitfields.
6986 SKIP_BITFIELDS(i , e, OriginalIvars);
6987 }
6988 else
6989 Ivars.push_back(OriginalIvars[i]);
6990 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006991
Fariborz Jahanianae932952012-02-10 20:47:10 +00006992 Result += "\nstatic ";
6993 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6994 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006995 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006996 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6997 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6998 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6999 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
7000 ObjCIvarDecl *IvarDecl = Ivars[i];
7001 if (i == 0)
7002 Result += "\t{{";
7003 else
7004 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007005 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007006 if (Ivars[i]->isBitField())
7007 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7008 else
7009 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007010 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007011
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007012 Result += "\"";
7013 if (Ivars[i]->isBitField())
7014 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7015 else
7016 Result += IvarDecl->getName();
7017 Result += "\", ";
7018
7019 QualType IVQT = IvarDecl->getType();
7020 if (IvarDecl->isBitField())
7021 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7022
Fariborz Jahanianae932952012-02-10 20:47:10 +00007023 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007024 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007025 IvarDecl);
7026 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7027 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7028
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007029 // FIXME. this alignment represents the host alignment and need be changed to
7030 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007031 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007032 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007033 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007034 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007035 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007036 if (i == e-1)
7037 Result += "}}\n";
7038 else
7039 Result += "},\n";
7040 }
7041 Result += "};\n";
7042 }
7043}
7044
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007045/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007046void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7047 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007048
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007049 // Do not synthesize the protocol more than once.
7050 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7051 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007052 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007053
7054 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7055 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007056 // Must write out all protocol definitions in current qualifier list,
7057 // and in their nested qualifiers before writing out current definition.
7058 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7059 E = PDecl->protocol_end(); I != E; ++I)
7060 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007061
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007062 // Construct method lists.
7063 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7064 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7065 for (ObjCProtocolDecl::instmeth_iterator
7066 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7067 I != E; ++I) {
7068 ObjCMethodDecl *MD = *I;
7069 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7070 OptInstanceMethods.push_back(MD);
7071 } else {
7072 InstanceMethods.push_back(MD);
7073 }
7074 }
7075
7076 for (ObjCProtocolDecl::classmeth_iterator
7077 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7078 I != E; ++I) {
7079 ObjCMethodDecl *MD = *I;
7080 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7081 OptClassMethods.push_back(MD);
7082 } else {
7083 ClassMethods.push_back(MD);
7084 }
7085 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007086 std::vector<ObjCMethodDecl *> AllMethods;
7087 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7088 AllMethods.push_back(InstanceMethods[i]);
7089 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7090 AllMethods.push_back(ClassMethods[i]);
7091 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7092 AllMethods.push_back(OptInstanceMethods[i]);
7093 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7094 AllMethods.push_back(OptClassMethods[i]);
7095
7096 Write__extendedMethodTypes_initializer(*this, Context, Result,
7097 AllMethods,
7098 "_OBJC_PROTOCOL_METHOD_TYPES_",
7099 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007100 // Protocol's super protocol list
7101 std::vector<ObjCProtocolDecl *> SuperProtocols;
7102 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7103 E = PDecl->protocol_end(); I != E; ++I)
7104 SuperProtocols.push_back(*I);
7105
7106 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7107 "_OBJC_PROTOCOL_REFS_",
7108 PDecl->getNameAsString());
7109
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007110 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007111 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007112 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007113
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007114 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007115 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007116 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007117
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007118 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007119 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007120 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007121
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007122 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007123 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007124 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007125
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007126 // Protocol's property metadata.
7127 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7128 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7129 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007130 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007131
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007132 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007133 /* Container */0,
7134 "_OBJC_PROTOCOL_PROPERTIES_",
7135 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007136
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007137 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007138 Result += "\n";
7139 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007140 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007141 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007142 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007143 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7144 Result += "\t0,\n"; // id is; is null
7145 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007146 if (SuperProtocols.size() > 0) {
7147 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7148 Result += PDecl->getNameAsString(); Result += ",\n";
7149 }
7150 else
7151 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007152 if (InstanceMethods.size() > 0) {
7153 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7154 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007155 }
7156 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007157 Result += "\t0,\n";
7158
7159 if (ClassMethods.size() > 0) {
7160 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7161 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007162 }
7163 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007164 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007165
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007166 if (OptInstanceMethods.size() > 0) {
7167 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7168 Result += PDecl->getNameAsString(); Result += ",\n";
7169 }
7170 else
7171 Result += "\t0,\n";
7172
7173 if (OptClassMethods.size() > 0) {
7174 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7175 Result += PDecl->getNameAsString(); Result += ",\n";
7176 }
7177 else
7178 Result += "\t0,\n";
7179
7180 if (ProtocolProperties.size() > 0) {
7181 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7182 Result += PDecl->getNameAsString(); Result += ",\n";
7183 }
7184 else
7185 Result += "\t0,\n";
7186
7187 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7188 Result += "\t0,\n";
7189
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007190 if (AllMethods.size() > 0) {
7191 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7192 Result += PDecl->getNameAsString();
7193 Result += "\n};\n";
7194 }
7195 else
7196 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007197
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007198 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007199 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007200 Result += "struct _protocol_t *";
7201 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7202 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7203 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007204
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007205 // Mark this protocol as having been generated.
7206 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7207 llvm_unreachable("protocol already synthesized");
7208
7209}
7210
7211void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7212 const ObjCList<ObjCProtocolDecl> &Protocols,
7213 StringRef prefix, StringRef ClassName,
7214 std::string &Result) {
7215 if (Protocols.empty()) return;
7216
7217 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007218 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007219
7220 // Output the top lovel protocol meta-data for the class.
7221 /* struct _objc_protocol_list {
7222 struct _objc_protocol_list *next;
7223 int protocol_count;
7224 struct _objc_protocol *class_protocols[];
7225 }
7226 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007227 Result += "\n";
7228 if (LangOpts.MicrosoftExt)
7229 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7230 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007231 Result += "\tstruct _objc_protocol_list *next;\n";
7232 Result += "\tint protocol_count;\n";
7233 Result += "\tstruct _objc_protocol *class_protocols[";
7234 Result += utostr(Protocols.size());
7235 Result += "];\n} _OBJC_";
7236 Result += prefix;
7237 Result += "_PROTOCOLS_";
7238 Result += ClassName;
7239 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7240 "{\n\t0, ";
7241 Result += utostr(Protocols.size());
7242 Result += "\n";
7243
7244 Result += "\t,{&_OBJC_PROTOCOL_";
7245 Result += Protocols[0]->getNameAsString();
7246 Result += " \n";
7247
7248 for (unsigned i = 1; i != Protocols.size(); i++) {
7249 Result += "\t ,&_OBJC_PROTOCOL_";
7250 Result += Protocols[i]->getNameAsString();
7251 Result += "\n";
7252 }
7253 Result += "\t }\n};\n";
7254}
7255
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007256/// hasObjCExceptionAttribute - Return true if this class or any super
7257/// class has the __objc_exception__ attribute.
7258/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7259static bool hasObjCExceptionAttribute(ASTContext &Context,
7260 const ObjCInterfaceDecl *OID) {
7261 if (OID->hasAttr<ObjCExceptionAttr>())
7262 return true;
7263 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7264 return hasObjCExceptionAttribute(Context, Super);
7265 return false;
7266}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007267
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007268void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7269 std::string &Result) {
7270 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7271
7272 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007273 if (CDecl->isImplicitInterfaceDecl())
7274 assert(false &&
7275 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007276
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007277 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007278 SmallVector<ObjCIvarDecl *, 8> IVars;
7279
7280 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7281 IVD; IVD = IVD->getNextIvar()) {
7282 // Ignore unnamed bit-fields.
7283 if (!IVD->getDeclName())
7284 continue;
7285 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007286 }
7287
Fariborz Jahanianae932952012-02-10 20:47:10 +00007288 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007289 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007290 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007291
7292 // Build _objc_method_list for class's instance methods if needed
7293 SmallVector<ObjCMethodDecl *, 32>
7294 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7295
7296 // If any of our property implementations have associated getters or
7297 // setters, produce metadata for them as well.
7298 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7299 PropEnd = IDecl->propimpl_end();
7300 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007301 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007302 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007303 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007304 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007305 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007306 if (!PD)
7307 continue;
7308 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007309 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007310 InstanceMethods.push_back(Getter);
7311 if (PD->isReadOnly())
7312 continue;
7313 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007314 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007315 InstanceMethods.push_back(Setter);
7316 }
7317
7318 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7319 "_OBJC_$_INSTANCE_METHODS_",
7320 IDecl->getNameAsString(), true);
7321
7322 SmallVector<ObjCMethodDecl *, 32>
7323 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7324
7325 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7326 "_OBJC_$_CLASS_METHODS_",
7327 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007328
7329 // Protocols referenced in class declaration?
7330 // Protocol's super protocol list
7331 std::vector<ObjCProtocolDecl *> RefedProtocols;
7332 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7333 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7334 E = Protocols.end();
7335 I != E; ++I) {
7336 RefedProtocols.push_back(*I);
7337 // Must write out all protocol definitions in current qualifier list,
7338 // and in their nested qualifiers before writing out current definition.
7339 RewriteObjCProtocolMetaData(*I, Result);
7340 }
7341
7342 Write_protocol_list_initializer(Context, Result,
7343 RefedProtocols,
7344 "_OBJC_CLASS_PROTOCOLS_$_",
7345 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007346
7347 // Protocol's property metadata.
7348 std::vector<ObjCPropertyDecl *> ClassProperties;
7349 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7350 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007351 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007352
7353 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007354 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007355 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007356 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007357
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007358
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007359 // Data for initializing _class_ro_t metaclass meta-data
7360 uint32_t flags = CLS_META;
7361 std::string InstanceSize;
7362 std::string InstanceStart;
7363
7364
7365 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7366 if (classIsHidden)
7367 flags |= OBJC2_CLS_HIDDEN;
7368
7369 if (!CDecl->getSuperClass())
7370 // class is root
7371 flags |= CLS_ROOT;
7372 InstanceSize = "sizeof(struct _class_t)";
7373 InstanceStart = InstanceSize;
7374 Write__class_ro_t_initializer(Context, Result, flags,
7375 InstanceStart, InstanceSize,
7376 ClassMethods,
7377 0,
7378 0,
7379 0,
7380 "_OBJC_METACLASS_RO_$_",
7381 CDecl->getNameAsString());
7382
7383
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007384 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007385 flags = CLS;
7386 if (classIsHidden)
7387 flags |= OBJC2_CLS_HIDDEN;
7388
7389 if (hasObjCExceptionAttribute(*Context, CDecl))
7390 flags |= CLS_EXCEPTION;
7391
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007392 if (!CDecl->getSuperClass())
7393 // class is root
7394 flags |= CLS_ROOT;
7395
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007396 InstanceSize.clear();
7397 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007398 if (!ObjCSynthesizedStructs.count(CDecl)) {
7399 InstanceSize = "0";
7400 InstanceStart = "0";
7401 }
7402 else {
7403 InstanceSize = "sizeof(struct ";
7404 InstanceSize += CDecl->getNameAsString();
7405 InstanceSize += "_IMPL)";
7406
7407 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7408 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007409 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007410 }
7411 else
7412 InstanceStart = InstanceSize;
7413 }
7414 Write__class_ro_t_initializer(Context, Result, flags,
7415 InstanceStart, InstanceSize,
7416 InstanceMethods,
7417 RefedProtocols,
7418 IVars,
7419 ClassProperties,
7420 "_OBJC_CLASS_RO_$_",
7421 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007422
7423 Write_class_t(Context, Result,
7424 "OBJC_METACLASS_$_",
7425 CDecl, /*metaclass*/true);
7426
7427 Write_class_t(Context, Result,
7428 "OBJC_CLASS_$_",
7429 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007430
7431 if (ImplementationIsNonLazy(IDecl))
7432 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007433
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007434}
7435
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007436void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7437 int ClsDefCount = ClassImplementation.size();
7438 if (!ClsDefCount)
7439 return;
7440 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7441 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7442 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7443 for (int i = 0; i < ClsDefCount; i++) {
7444 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7445 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7446 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7447 Result += CDecl->getName(); Result += ",\n";
7448 }
7449 Result += "};\n";
7450}
7451
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007452void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7453 int ClsDefCount = ClassImplementation.size();
7454 int CatDefCount = CategoryImplementation.size();
7455
7456 // For each implemented class, write out all its meta data.
7457 for (int i = 0; i < ClsDefCount; i++)
7458 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7459
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007460 RewriteClassSetupInitHook(Result);
7461
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007462 // For each implemented category, write out all its meta data.
7463 for (int i = 0; i < CatDefCount; i++)
7464 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7465
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007466 RewriteCategorySetupInitHook(Result);
7467
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007468 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007469 if (LangOpts.MicrosoftExt)
7470 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007471 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7472 Result += llvm::utostr(ClsDefCount); Result += "]";
7473 Result +=
7474 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7475 "regular,no_dead_strip\")))= {\n";
7476 for (int i = 0; i < ClsDefCount; i++) {
7477 Result += "\t&OBJC_CLASS_$_";
7478 Result += ClassImplementation[i]->getNameAsString();
7479 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007480 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007481 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007482
7483 if (!DefinedNonLazyClasses.empty()) {
7484 if (LangOpts.MicrosoftExt)
7485 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7486 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7487 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7488 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7489 Result += ",\n";
7490 }
7491 Result += "};\n";
7492 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007493 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007494
7495 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007496 if (LangOpts.MicrosoftExt)
7497 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007498 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7499 Result += llvm::utostr(CatDefCount); Result += "]";
7500 Result +=
7501 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7502 "regular,no_dead_strip\")))= {\n";
7503 for (int i = 0; i < CatDefCount; i++) {
7504 Result += "\t&_OBJC_$_CATEGORY_";
7505 Result +=
7506 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7507 Result += "_$_";
7508 Result += CategoryImplementation[i]->getNameAsString();
7509 Result += ",\n";
7510 }
7511 Result += "};\n";
7512 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007513
7514 if (!DefinedNonLazyCategories.empty()) {
7515 if (LangOpts.MicrosoftExt)
7516 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7517 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7518 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7519 Result += "\t&_OBJC_$_CATEGORY_";
7520 Result +=
7521 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7522 Result += "_$_";
7523 Result += DefinedNonLazyCategories[i]->getNameAsString();
7524 Result += ",\n";
7525 }
7526 Result += "};\n";
7527 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007528}
7529
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007530void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7531 if (LangOpts.MicrosoftExt)
7532 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7533
7534 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7535 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007536 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007537}
7538
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007539/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7540/// implementation.
7541void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7542 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007543 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007544 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7545 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007546 ObjCCategoryDecl *CDecl
7547 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007548
7549 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007550 FullCategoryName += "_$_";
7551 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007552
7553 // Build _objc_method_list for class's instance methods if needed
7554 SmallVector<ObjCMethodDecl *, 32>
7555 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7556
7557 // If any of our property implementations have associated getters or
7558 // setters, produce metadata for them as well.
7559 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7560 PropEnd = IDecl->propimpl_end();
7561 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007562 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007563 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007564 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007565 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007566 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007567 if (!PD)
7568 continue;
7569 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7570 InstanceMethods.push_back(Getter);
7571 if (PD->isReadOnly())
7572 continue;
7573 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7574 InstanceMethods.push_back(Setter);
7575 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007576
Fariborz Jahanian61186122012-02-17 18:40:41 +00007577 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7578 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7579 FullCategoryName, true);
7580
7581 SmallVector<ObjCMethodDecl *, 32>
7582 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7583
7584 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7585 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7586 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007587
7588 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007589 // Protocol's super protocol list
7590 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007591 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7592 E = CDecl->protocol_end();
7593
7594 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007595 RefedProtocols.push_back(*I);
7596 // Must write out all protocol definitions in current qualifier list,
7597 // and in their nested qualifiers before writing out current definition.
7598 RewriteObjCProtocolMetaData(*I, Result);
7599 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007600
Fariborz Jahanian61186122012-02-17 18:40:41 +00007601 Write_protocol_list_initializer(Context, Result,
7602 RefedProtocols,
7603 "_OBJC_CATEGORY_PROTOCOLS_$_",
7604 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007605
Fariborz Jahanian61186122012-02-17 18:40:41 +00007606 // Protocol's property metadata.
7607 std::vector<ObjCPropertyDecl *> ClassProperties;
7608 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7609 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007610 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007611
Fariborz Jahanian61186122012-02-17 18:40:41 +00007612 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007613 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007614 "_OBJC_$_PROP_LIST_",
7615 FullCategoryName);
7616
7617 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007618 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007619 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007620 InstanceMethods,
7621 ClassMethods,
7622 RefedProtocols,
7623 ClassProperties);
7624
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007625 // Determine if this category is also "non-lazy".
7626 if (ImplementationIsNonLazy(IDecl))
7627 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007628
7629}
7630
7631void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7632 int CatDefCount = CategoryImplementation.size();
7633 if (!CatDefCount)
7634 return;
7635 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7636 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7637 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7638 for (int i = 0; i < CatDefCount; i++) {
7639 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7640 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7641 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7642 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7643 Result += ClassDecl->getName();
7644 Result += "_$_";
7645 Result += CatDecl->getName();
7646 Result += ",\n";
7647 }
7648 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007649}
7650
7651// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7652/// class methods.
7653template<typename MethodIterator>
7654void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7655 MethodIterator MethodEnd,
7656 bool IsInstanceMethod,
7657 StringRef prefix,
7658 StringRef ClassName,
7659 std::string &Result) {
7660 if (MethodBegin == MethodEnd) return;
7661
7662 if (!objc_impl_method) {
7663 /* struct _objc_method {
7664 SEL _cmd;
7665 char *method_types;
7666 void *_imp;
7667 }
7668 */
7669 Result += "\nstruct _objc_method {\n";
7670 Result += "\tSEL _cmd;\n";
7671 Result += "\tchar *method_types;\n";
7672 Result += "\tvoid *_imp;\n";
7673 Result += "};\n";
7674
7675 objc_impl_method = true;
7676 }
7677
7678 // Build _objc_method_list for class's methods if needed
7679
7680 /* struct {
7681 struct _objc_method_list *next_method;
7682 int method_count;
7683 struct _objc_method method_list[];
7684 }
7685 */
7686 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007687 Result += "\n";
7688 if (LangOpts.MicrosoftExt) {
7689 if (IsInstanceMethod)
7690 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7691 else
7692 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7693 }
7694 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007695 Result += "\tstruct _objc_method_list *next_method;\n";
7696 Result += "\tint method_count;\n";
7697 Result += "\tstruct _objc_method method_list[";
7698 Result += utostr(NumMethods);
7699 Result += "];\n} _OBJC_";
7700 Result += prefix;
7701 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7702 Result += "_METHODS_";
7703 Result += ClassName;
7704 Result += " __attribute__ ((used, section (\"__OBJC, __";
7705 Result += IsInstanceMethod ? "inst" : "cls";
7706 Result += "_meth\")))= ";
7707 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7708
7709 Result += "\t,{{(SEL)\"";
7710 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7711 std::string MethodTypeString;
7712 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7713 Result += "\", \"";
7714 Result += MethodTypeString;
7715 Result += "\", (void *)";
7716 Result += MethodInternalNames[*MethodBegin];
7717 Result += "}\n";
7718 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7719 Result += "\t ,{(SEL)\"";
7720 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7721 std::string MethodTypeString;
7722 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7723 Result += "\", \"";
7724 Result += MethodTypeString;
7725 Result += "\", (void *)";
7726 Result += MethodInternalNames[*MethodBegin];
7727 Result += "}\n";
7728 }
7729 Result += "\t }\n};\n";
7730}
7731
7732Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7733 SourceRange OldRange = IV->getSourceRange();
7734 Expr *BaseExpr = IV->getBase();
7735
7736 // Rewrite the base, but without actually doing replaces.
7737 {
7738 DisableReplaceStmtScope S(*this);
7739 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7740 IV->setBase(BaseExpr);
7741 }
7742
7743 ObjCIvarDecl *D = IV->getDecl();
7744
7745 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007746
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007747 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7748 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007749 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007750 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7751 // lookup which class implements the instance variable.
7752 ObjCInterfaceDecl *clsDeclared = 0;
7753 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7754 clsDeclared);
7755 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7756
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007757 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007758 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007759 if (D->isBitField())
7760 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7761 else
7762 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007763
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007764 ReferencedIvars[clsDeclared].insert(D);
7765
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007766 // cast offset to "char *".
7767 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7768 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007769 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007770 BaseExpr);
7771 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7772 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7773 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007774 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7775 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007776 SourceLocation());
7777 BinaryOperator *addExpr =
7778 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7779 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007780 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007781 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007782 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7783 SourceLocation(),
7784 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007785 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007786 if (D->isBitField())
7787 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007788
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007789 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007790 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007791 RD = RD->getDefinition();
7792 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007793 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007794 ObjCContainerDecl *CDecl =
7795 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7796 // ivar in class extensions requires special treatment.
7797 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7798 CDecl = CatDecl->getClassInterface();
7799 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007800 RecName += "_IMPL";
7801 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7802 SourceLocation(), SourceLocation(),
7803 &Context->Idents.get(RecName.c_str()));
7804 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7805 unsigned UnsignedIntSize =
7806 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7807 Expr *Zero = IntegerLiteral::Create(*Context,
7808 llvm::APInt(UnsignedIntSize, 0),
7809 Context->UnsignedIntTy, SourceLocation());
7810 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7811 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7812 Zero);
7813 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7814 SourceLocation(),
7815 &Context->Idents.get(D->getNameAsString()),
7816 IvarT, 0,
7817 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007818 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007819 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7820 FD->getType(), VK_LValue,
7821 OK_Ordinary);
7822 IvarT = Context->getDecltypeType(ME, ME->getType());
7823 }
7824 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007825 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007826 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007827
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007828 castExpr = NoTypeInfoCStyleCastExpr(Context,
7829 castT,
7830 CK_BitCast,
7831 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007832
7833
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007834 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007835 VK_LValue, OK_Ordinary,
7836 SourceLocation());
7837 PE = new (Context) ParenExpr(OldRange.getBegin(),
7838 OldRange.getEnd(),
7839 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007840
7841 if (D->isBitField()) {
7842 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7843 SourceLocation(),
7844 &Context->Idents.get(D->getNameAsString()),
7845 D->getType(), 0,
7846 /*BitWidth=*/D->getBitWidth(),
7847 /*Mutable=*/true,
7848 ICIS_NoInit);
7849 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7850 FD->getType(), VK_LValue,
7851 OK_Ordinary);
7852 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007853
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007854 }
7855 else
7856 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007857 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007858
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007859 ReplaceStmtWithRange(IV, Replacement, OldRange);
7860 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007861}