Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// Hacks and fun related to the code rewriter.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Rewrite/Frontend/ASTConsumers.h"
14
#include "clang/AST/AST.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/ParentMap.h"
18
#include "clang/Basic/CharInfo.h"
19
#include "clang/Basic/Diagnostic.h"
20
#include "clang/Basic/IdentifierTable.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Config/config.h"
23
#include "clang/Lex/Lexer.h"
24
#include "clang/Rewrite/Core/Rewriter.h"
25
#include "llvm/ADT/DenseSet.h"
26
#include "llvm/ADT/SmallPtrSet.h"
27
#include "llvm/ADT/StringExtras.h"
28
#include "llvm/Support/MemoryBuffer.h"
29
#include "llvm/Support/raw_ostream.h"
30
#include <memory>
31
32
#if CLANG_ENABLE_OBJC_REWRITER
33
34
using namespace clang;
35
using llvm::utostr;
36
37
namespace {
38
  class RewriteObjC : public ASTConsumer {
39
  protected:
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
    std::unique_ptr<raw_ostream> OutFile;
75
    std::string Preamble;
76
77
    TypeDecl *ProtocolTypeDecl;
78
    VarDecl *GlobalVarDecl;
79
    unsigned RewriteFailedDiag;
80
    // ObjC string constant support.
81
    unsigned NumObjCStringLiterals;
82
    VarDecl *ConstantStringClassReference;
83
    RecordDecl *NSStringRecord;
84
85
    // ObjC foreach break/continue generation support.
86
    int BcLabelCount;
87
88
    unsigned TryFinallyContainsReturnDiag;
89
    // Needed for super.
90
    ObjCMethodDecl *CurMethodDef;
91
    RecordDecl *SuperStructDecl;
92
    RecordDecl *ConstantStringDecl;
93
94
    FunctionDecl *MsgSendFunctionDecl;
95
    FunctionDecl *MsgSendSuperFunctionDecl;
96
    FunctionDecl *MsgSendStretFunctionDecl;
97
    FunctionDecl *MsgSendSuperStretFunctionDecl;
98
    FunctionDecl *MsgSendFpretFunctionDecl;
99
    FunctionDecl *GetClassFunctionDecl;
100
    FunctionDecl *GetMetaClassFunctionDecl;
101
    FunctionDecl *GetSuperClassFunctionDecl;
102
    FunctionDecl *SelGetUidFunctionDecl;
103
    FunctionDecl *CFStringFunctionDecl;
104
    FunctionDecl *SuperConstructorFunctionDecl;
105
    FunctionDecl *CurFunctionDef;
106
    FunctionDecl *CurFunctionDeclToDeclareForBlock;
107
108
    /* Misc. containers needed for meta-data rewrite. */
109
    SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110
    SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112
    llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
113
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
114
    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
115
    SmallVector<Stmt *, 32> Stmts;
116
    SmallVector<int, 8> ObjCBcLabelNo;
117
    // Remember all the @protocol(<expr>) expressions.
118
    llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
119
120
    llvm::DenseSet<uint64_t> CopyDestroyCache;
121
122
    // Block expressions.
123
    SmallVector<BlockExpr *, 32> Blocks;
124
    SmallVector<int, 32> InnerDeclRefsCount;
125
    SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
126
127
    SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
128
129
    // Block related declarations.
130
    SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132
    SmallVector<ValueDecl *, 8> BlockByRefDecls;
133
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
134
    llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
135
    llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136
    llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
137
138
    llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
139
140
    // This maps an original source AST to it's rewritten form. This allows
141
    // us to avoid rewriting the same node twice (which is very uncommon).
142
    // This is needed to support some of the exotic property rewriting.
143
    llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
144
145
    // Needed for header files being rewritten
146
    bool IsHeader;
147
    bool SilenceRewriteMacroWarning;
148
    bool objc_impl_method;
149
150
    bool DisableReplaceStmt;
151
    class DisableReplaceStmtScope {
152
      RewriteObjC &R;
153
      bool SavedValue;
154
155
    public:
156
      DisableReplaceStmtScope(RewriteObjC &R)
157
79
        : R(R), SavedValue(R.DisableReplaceStmt) {
158
79
        R.DisableReplaceStmt = true;
159
79
      }
160
161
79
      ~DisableReplaceStmtScope() {
162
79
        R.DisableReplaceStmt = SavedValue;
163
79
      }
164
    };
165
166
    void InitializeCommon(ASTContext &context);
167
168
  public:
169
    // Top Level Driver code.
170
439
    bool HandleTopLevelDecl(DeclGroupRef D) override {
171
949
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I510
) {
172
533
        if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173
135
          if (!Class->isThisDeclarationADefinition()) {
174
17
            RewriteForwardClassDecl(D);
175
17
            break;
176
17
          }
177
516
        }
178
516
179
516
        if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180
27
          if (!Proto->isThisDeclarationADefinition()) {
181
6
            RewriteForwardProtocolDecl(D);
182
6
            break;
183
6
          }
184
510
        }
185
510
186
510
        HandleTopLevelSingleDecl(*I);
187
510
      }
188
439
      return true;
189
439
    }
190
191
    void HandleTopLevelSingleDecl(Decl *D);
192
    void HandleDeclInMainFile(Decl *D);
193
    RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
194
                DiagnosticsEngine &D, const LangOptions &LOpts,
195
                bool silenceMacroWarn);
196
197
86
    ~RewriteObjC() override {}
198
199
    void HandleTranslationUnit(ASTContext &C) override;
200
201
227
    void ReplaceStmt(Stmt *Old, Stmt *New) {
202
227
      ReplaceStmtWithRange(Old, New, Old->getSourceRange());
203
227
    }
204
205
306
    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
206
306
      assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
207
306
208
306
      Stmt *ReplacingStmt = ReplacedNodes[Old];
209
306
      if (ReplacingStmt)
210
0
        return; // We can't rewrite the same node twice.
211
306
212
306
      if (DisableReplaceStmt)
213
24
        return;
214
282
215
282
      // Measure the old text.
216
282
      int Size = Rewrite.getRangeSize(SrcRange);
217
282
      if (Size == -1) {
218
0
        Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
219
0
            << Old->getSourceRange();
220
0
        return;
221
0
      }
222
282
      // Get the new text.
223
282
      std::string SStr;
224
282
      llvm::raw_string_ostream S(SStr);
225
282
      New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
226
282
      const std::string &Str = S.str();
227
282
228
282
      // If replacement succeeded or warning disabled return with no warning.
229
282
      if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
230
282
        ReplacedNodes[Old] = New;
231
282
        return;
232
282
      }
233
0
      if (SilenceRewriteMacroWarning)
234
0
        return;
235
0
      Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
236
0
          << Old->getSourceRange();
237
0
    }
238
239
    void InsertText(SourceLocation Loc, StringRef Str,
240
817
                    bool InsertAfter = true) {
241
817
      // If insertion succeeded or warning disabled return with no warning.
242
817
      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
243
817
          
SilenceRewriteMacroWarning0
)
244
817
        return;
245
0
246
0
      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
247
0
    }
248
249
    void ReplaceText(SourceLocation Start, unsigned OrigLength,
250
599
                     StringRef Str) {
251
599
      // If removal succeeded or warning disabled return with no warning.
252
599
      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
253
599
          
SilenceRewriteMacroWarning0
)
254
599
        return;
255
0
256
0
      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
257
0
    }
258
259
    // Syntactic Rewriting.
260
    void RewriteRecordBody(RecordDecl *RD);
261
    void RewriteInclude();
262
    void RewriteForwardClassDecl(DeclGroupRef D);
263
    void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
264
    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
265
                                     const std::string &typedefString);
266
    void RewriteImplementations();
267
    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
268
                                 ObjCImplementationDecl *IMD,
269
                                 ObjCCategoryImplDecl *CID);
270
    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
271
    void RewriteImplementationDecl(Decl *Dcl);
272
    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
273
                               ObjCMethodDecl *MDecl, std::string &ResultStr);
274
    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
275
                               const FunctionType *&FPRetType);
276
    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
277
                            ValueDecl *VD, bool def=false);
278
    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
279
    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
280
    void RewriteForwardProtocolDecl(DeclGroupRef D);
281
    void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
282
    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
283
    void RewriteProperty(ObjCPropertyDecl *prop);
284
    void RewriteFunctionDecl(FunctionDecl *FD);
285
    void RewriteBlockPointerType(std::string& Str, QualType Type);
286
    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
287
    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
288
    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
289
    void RewriteTypeOfDecl(VarDecl *VD);
290
    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
291
292
    // Expression Rewriting.
293
    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
294
    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
295
    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
296
    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
297
    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
298
    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
299
    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
300
    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
301
    void RewriteTryReturnStmts(Stmt *S);
302
    void RewriteSyncReturnStmts(Stmt *S, std::string buf);
303
    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
304
    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
305
    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
306
    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307
                                       SourceLocation OrigEnd);
308
    Stmt *RewriteBreakStmt(BreakStmt *S);
309
    Stmt *RewriteContinueStmt(ContinueStmt *S);
310
    void RewriteCastExpr(CStyleCastExpr *CE);
311
312
    // Block rewriting.
313
    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
314
315
    // Block specific rewrite rules.
316
    void RewriteBlockPointerDecl(NamedDecl *VD);
317
    void RewriteByRefVar(VarDecl *VD);
318
    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
319
    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
320
    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
321
322
    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
323
                                      std::string &Result);
324
325
    void Initialize(ASTContext &context) override = 0;
326
327
    // Metadata Rewriting.
328
    virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
329
    virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
330
                                                 StringRef prefix,
331
                                                 StringRef ClassName,
332
                                                 std::string &Result) = 0;
333
    virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
334
                                             std::string &Result) = 0;
335
    virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336
                                     StringRef prefix,
337
                                     StringRef ClassName,
338
                                     std::string &Result) = 0;
339
    virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
340
                                          std::string &Result) = 0;
341
342
    // Rewriting ivar access
343
    virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
344
    virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
345
                                         std::string &Result) = 0;
346
347
    // Misc. AST transformation routines. Sometimes they end up calling
348
    // rewriting routines on the new ASTs.
349
    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
350
                                           ArrayRef<Expr *> Args,
351
                                           SourceLocation StartLoc=SourceLocation(),
352
                                           SourceLocation EndLoc=SourceLocation());
353
    CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
354
                                        QualType msgSendType,
355
                                        QualType returnType,
356
                                        SmallVectorImpl<QualType> &ArgTypes,
357
                                        SmallVectorImpl<Expr*> &MsgExprs,
358
                                        ObjCMethodDecl *Method);
359
    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360
                           SourceLocation StartLoc=SourceLocation(),
361
                           SourceLocation EndLoc=SourceLocation());
362
363
    void SynthCountByEnumWithState(std::string &buf);
364
    void SynthMsgSendFunctionDecl();
365
    void SynthMsgSendSuperFunctionDecl();
366
    void SynthMsgSendStretFunctionDecl();
367
    void SynthMsgSendFpretFunctionDecl();
368
    void SynthMsgSendSuperStretFunctionDecl();
369
    void SynthGetClassFunctionDecl();
370
    void SynthGetMetaClassFunctionDecl();
371
    void SynthGetSuperClassFunctionDecl();
372
    void SynthSelGetUidFunctionDecl();
373
    void SynthSuperConstructorFunctionDecl();
374
375
    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
376
    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
377
                                      StringRef funcName, std::string Tag);
378
    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
379
                                      StringRef funcName, std::string Tag);
380
    std::string SynthesizeBlockImpl(BlockExpr *CE,
381
                                    std::string Tag, std::string Desc);
382
    std::string SynthesizeBlockDescriptor(std::string DescTag,
383
                                          std::string ImplTag,
384
                                          int i, StringRef funcName,
385
                                          unsigned hasCopy);
386
    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
387
    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
388
                                 StringRef FunName);
389
    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390
    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
391
            const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
392
393
    // Misc. helper routines.
394
    QualType getProtocolType();
395
    void WarnAboutReturnGotoStmts(Stmt *S);
396
    void HasReturnStmts(Stmt *S, bool &hasReturns);
397
    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398
    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399
    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401
    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
402
    void CollectBlockDeclRefInfo(BlockExpr *Exp);
403
    void GetBlockDeclRefExprs(Stmt *S);
404
    void GetInnerBlockDeclRefExprs(Stmt *S,
405
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
406
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
407
408
    // We avoid calling Type::isBlockPointerType(), since it operates on the
409
    // canonical type. We only care if the top-level type is a closure pointer.
410
845
    bool isTopLevelBlockPointerType(QualType T) {
411
845
      return isa<BlockPointerType>(T);
412
845
    }
413
414
    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415
    /// to a function pointer type and upon success, returns true; false
416
    /// otherwise.
417
324
    bool convertBlockPointerToFunctionPointer(QualType &T) {
418
324
      if (isTopLevelBlockPointerType(T)) {
419
14
        const BlockPointerType *BPT = T->getAs<BlockPointerType>();
420
14
        T = Context->getPointerType(BPT->getPointeeType());
421
14
        return true;
422
14
      }
423
310
      return false;
424
310
    }
425
426
    bool needToScanForQualifiers(QualType T);
427
    QualType getSuperStructType();
428
    QualType getConstantStringStructType();
429
    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430
    bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
432
109
    void convertToUnqualifiedObjCType(QualType &T) {
433
109
      if (T->isObjCQualifiedIdType())
434
2
        T = Context->getObjCIdType();
435
107
      else if (T->isObjCQualifiedClassType())
436
0
        T = Context->getObjCClassType();
437
107
      else if (T->isObjCObjectPointerType() &&
438
107
               
T->getPointeeType()->isObjCQualifiedInterfaceType()56
) {
439
12
        if (const ObjCObjectPointerType * OBJPT =
440
12
              T->getAsObjCInterfacePointerType()) {
441
12
          const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442
12
          T = QualType(IFaceT, 0);
443
12
          T = Context->getPointerType(T);
444
12
        }
445
12
     }
446
109
    }
447
448
    // FIXME: This predicate seems like it would be useful to add to ASTContext.
449
42
    bool isObjCType(QualType T) {
450
42
      if (!LangOpts.ObjC)
451
0
        return false;
452
42
453
42
      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
454
42
455
42
      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456
42
          
OCT == Context->getCanonicalType(Context->getObjCClassType())35
)
457
7
        return true;
458
35
459
35
      if (const PointerType *PT = OCT->getAs<PointerType>()) {
460
2
        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
461
2
            PT->getPointeeType()->isObjCQualifiedIdType())
462
0
          return true;
463
35
      }
464
35
      return false;
465
35
    }
466
    bool PointerTypeTakesAnyBlockArguments(QualType QT);
467
    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
468
    void GetExtentOfArgList(const char *Name, const char *&LParen,
469
                            const char *&RParen);
470
471
43
    void QuoteDoublequotes(std::string &From, std::string &To) {
472
347
      for (unsigned i = 0; i < From.length(); 
i++304
) {
473
304
        if (From[i] == '"')
474
38
          To += "\\\"";
475
266
        else
476
266
          To += From[i];
477
304
      }
478
43
    }
479
480
    QualType getSimpleFunctionType(QualType result,
481
                                   ArrayRef<QualType> args,
482
435
                                   bool variadic = false) {
483
435
      if (result == Context->getObjCInstanceType())
484
0
        result =  Context->getObjCIdType();
485
435
      FunctionProtoType::ExtProtoInfo fpi;
486
435
      fpi.Variadic = variadic;
487
435
      return Context->getFunctionType(result, args, fpi);
488
435
    }
489
490
    // Helper function: create a CStyleCastExpr with trivial type source info.
491
    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
492
620
                                             CastKind Kind, Expr *E) {
493
620
      TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
494
620
      return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
495
620
                                    TInfo, SourceLocation(), SourceLocation());
496
620
    }
497
498
139
    StringLiteral *getStringLiteral(StringRef Str) {
499
139
      QualType StrType = Context->getConstantArrayType(
500
139
          Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
501
139
          0);
502
139
      return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
503
139
                                   /*Pascal=*/false, StrType, SourceLocation());
504
139
    }
505
  };
506
507
  class RewriteObjCFragileABI : public RewriteObjC {
508
  public:
509
    RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
510
                          DiagnosticsEngine &D, const LangOptions &LOpts,
511
                          bool silenceMacroWarn)
512
86
        : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
513
514
86
    ~RewriteObjCFragileABI() override {}
515
    void Initialize(ASTContext &context) override;
516
517
    // Rewriting metadata
518
    template<typename MethodIterator>
519
    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
520
                                    MethodIterator MethodEnd,
521
                                    bool IsInstanceMethod,
522
                                    StringRef prefix,
523
                                    StringRef ClassName,
524
                                    std::string &Result);
525
    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
526
                                     StringRef prefix, StringRef ClassName,
527
                                     std::string &Result) override;
528
    void RewriteObjCProtocolListMetaData(
529
          const ObjCList<ObjCProtocolDecl> &Prots,
530
          StringRef prefix, StringRef ClassName, std::string &Result) override;
531
    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
532
                                  std::string &Result) override;
533
    void RewriteMetaDataIntoBuffer(std::string &Result) override;
534
    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
535
                                     std::string &Result) override;
536
537
    // Rewriting ivar
538
    void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
539
                                      std::string &Result) override;
540
    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
541
  };
542
} // end anonymous namespace
543
544
void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
545
136
                                                   NamedDecl *D) {
546
136
  if (const FunctionProtoType *fproto
547
113
      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
548
113
    for (const auto &I : fproto->param_types())
549
101
      if (isTopLevelBlockPointerType(I)) {
550
20
        // All the args are checked/rewritten. Don't call twice!
551
20
        RewriteBlockPointerDecl(D);
552
20
        break;
553
20
      }
554
113
  }
555
136
}
556
557
1
void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
558
1
  const PointerType *PT = funcType->getAs<PointerType>();
559
1
  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
560
0
    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
561
1
}
562
563
86
static bool IsHeaderFile(const std::string &Filename) {
564
86
  std::string::size_type DotPos = Filename.rfind('.');
565
86
566
86
  if (DotPos == std::string::npos) {
567
0
    // no file extension
568
0
    return false;
569
0
  }
570
86
571
86
  std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
572
86
  // C header: .h
573
86
  // C++ header: .hh or .H;
574
86
  return Ext == "h" || Ext == "hh" || Ext == "H";
575
86
}
576
577
RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
578
                         DiagnosticsEngine &D, const LangOptions &LOpts,
579
                         bool silenceMacroWarn)
580
    : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
581
86
      SilenceRewriteMacroWarning(silenceMacroWarn) {
582
86
  IsHeader = IsHeaderFile(inFile);
583
86
  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
584
86
               "rewriting sub-expression within a macro (may not be correct)");
585
86
  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
586
86
               DiagnosticsEngine::Warning,
587
86
               "rewriter doesn't support user-specified control flow semantics "
588
86
               "for @try/@finally (code may not execute properly)");
589
86
}
590
591
std::unique_ptr<ASTConsumer>
592
clang::CreateObjCRewriter(const std::string &InFile,
593
                          std::unique_ptr<raw_ostream> OS,
594
                          DiagnosticsEngine &Diags, const LangOptions &LOpts,
595
86
                          bool SilenceRewriteMacroWarning) {
596
86
  return llvm::make_unique<RewriteObjCFragileABI>(
597
86
      InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
598
86
}
599
600
86
void RewriteObjC::InitializeCommon(ASTContext &context) {
601
86
  Context = &context;
602
86
  SM = &Context->getSourceManager();
603
86
  TUDecl = Context->getTranslationUnitDecl();
604
86
  MsgSendFunctionDecl = nullptr;
605
86
  MsgSendSuperFunctionDecl = nullptr;
606
86
  MsgSendStretFunctionDecl = nullptr;
607
86
  MsgSendSuperStretFunctionDecl = nullptr;
608
86
  MsgSendFpretFunctionDecl = nullptr;
609
86
  GetClassFunctionDecl = nullptr;
610
86
  GetMetaClassFunctionDecl = nullptr;
611
86
  GetSuperClassFunctionDecl = nullptr;
612
86
  SelGetUidFunctionDecl = nullptr;
613
86
  CFStringFunctionDecl = nullptr;
614
86
  ConstantStringClassReference = nullptr;
615
86
  NSStringRecord = nullptr;
616
86
  CurMethodDef = nullptr;
617
86
  CurFunctionDef = nullptr;
618
86
  CurFunctionDeclToDeclareForBlock = nullptr;
619
86
  GlobalVarDecl = nullptr;
620
86
  SuperStructDecl = nullptr;
621
86
  ProtocolTypeDecl = nullptr;
622
86
  ConstantStringDecl = nullptr;
623
86
  BcLabelCount = 0;
624
86
  SuperConstructorFunctionDecl = nullptr;
625
86
  NumObjCStringLiterals = 0;
626
86
  PropParentMap = nullptr;
627
86
  CurrentBody = nullptr;
628
86
  DisableReplaceStmt = false;
629
86
  objc_impl_method = false;
630
86
631
86
  // Get the ID and start/end of the main file.
632
86
  MainFileID = SM->getMainFileID();
633
86
  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634
86
  MainFileStart = MainBuf->getBufferStart();
635
86
  MainFileEnd = MainBuf->getBufferEnd();
636
86
637
86
  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
638
86
}
639
640
//===----------------------------------------------------------------------===//
641
// Top Level Driver Code
642
//===----------------------------------------------------------------------===//
643
644
524
void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
645
524
  if (Diags.hasErrorOccurred())
646
0
    return;
647
524
648
524
  // Two cases: either the decl could be in the main file, or it could be in a
649
524
  // #included file.  If the former, rewrite it now.  If the later, check to see
650
524
  // if we rewrote the #include/#import.
651
524
  SourceLocation Loc = D->getLocation();
652
524
  Loc = SM->getExpansionLoc(Loc);
653
524
654
524
  // If this is for a builtin, ignore it.
655
524
  if (Loc.isInvalid()) 
return0
;
656
524
657
524
  // Look for built-in declarations that we need to refer during the rewrite.
658
524
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
659
136
    RewriteFunctionDecl(FD);
660
388
  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
661
17
    // declared in <Foundation/NSString.h>
662
17
    if (FVD->getName() == "_NSConstantStringClassReference") {
663
0
      ConstantStringClassReference = FVD;
664
0
      return;
665
0
    }
666
371
  } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667
118
    if (ID->isThisDeclarationADefinition())
668
118
      RewriteInterfaceDecl(ID);
669
253
  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
670
6
    RewriteCategoryDecl(CD);
671
247
  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
672
21
    if (PD->isThisDeclarationADefinition())
673
21
      RewriteProtocolDecl(PD);
674
226
  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675
13
    // Recurse into linkage specifications
676
13
    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677
13
                                 DIEnd = LSD->decls_end();
678
27
         DI != DIEnd; ) {
679
14
      if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680
0
        if (!IFace->isThisDeclarationADefinition()) {
681
0
          SmallVector<Decl *, 8> DG;
682
0
          SourceLocation StartLoc = IFace->getBeginLoc();
683
0
          do {
684
0
            if (isa<ObjCInterfaceDecl>(*DI) &&
685
0
                !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686
0
                StartLoc == (*DI)->getBeginLoc())
687
0
              DG.push_back(*DI);
688
0
            else
689
0
              break;
690
0
691
0
            ++DI;
692
0
          } while (DI != DIEnd);
693
0
          RewriteForwardClassDecl(DG);
694
0
          continue;
695
0
        }
696
14
      }
697
14
698
14
      if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699
0
        if (!Proto->isThisDeclarationADefinition()) {
700
0
          SmallVector<Decl *, 8> DG;
701
0
          SourceLocation StartLoc = Proto->getBeginLoc();
702
0
          do {
703
0
            if (isa<ObjCProtocolDecl>(*DI) &&
704
0
                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705
0
                StartLoc == (*DI)->getBeginLoc())
706
0
              DG.push_back(*DI);
707
0
            else
708
0
              break;
709
0
710
0
            ++DI;
711
0
          } while (DI != DIEnd);
712
0
          RewriteForwardProtocolDecl(DG);
713
0
          continue;
714
0
        }
715
14
      }
716
14
717
14
      HandleTopLevelSingleDecl(*DI);
718
14
      ++DI;
719
14
    }
720
13
  }
721
524
  // If we have a decl in the main file, see if we should rewrite it.
722
524
  if (SM->isWrittenInMainFile(Loc))
723
522
    return HandleDeclInMainFile(D);
724
524
}
725
726
//===----------------------------------------------------------------------===//
727
// Syntactic (non-AST) Rewriting Code
728
//===----------------------------------------------------------------------===//
729
730
86
void RewriteObjC::RewriteInclude() {
731
86
  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
732
86
  StringRef MainBuf = SM->getBufferData(MainFileID);
733
86
  const char *MainBufStart = MainBuf.begin();
734
86
  const char *MainBufEnd = MainBuf.end();
735
86
  size_t ImportLen = strlen("import");
736
86
737
86
  // Loop over the whole file, looking for includes.
738
60.2k
  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; 
++BufPtr60.1k
) {
739
60.1k
    if (*BufPtr == '#') {
740
23
      if (++BufPtr == MainBufEnd)
741
0
        return;
742
44
      
while (23
*BufPtr == ' ' ||
*BufPtr == '\t'23
)
743
21
        if (++BufPtr == MainBufEnd)
744
0
          return;
745
23
      if (!strncmp(BufPtr, "import", ImportLen)) {
746
0
        // replace import with include
747
0
        SourceLocation ImportLoc =
748
0
          LocStart.getLocWithOffset(BufPtr-MainBufStart);
749
0
        ReplaceText(ImportLoc, ImportLen, "include");
750
0
        BufPtr += ImportLen;
751
0
      }
752
23
    }
753
60.1k
  }
754
86
}
755
756
3
static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757
3
  const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
758
3
  std::string S;
759
3
  S = "((struct ";
760
3
  S += ClassDecl->getIdentifier()->getName();
761
3
  S += "_IMPL *)self)->";
762
3
  S += OID->getName();
763
3
  return S;
764
3
}
765
766
void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767
                                          ObjCImplementationDecl *IMD,
768
12
                                          ObjCCategoryImplDecl *CID) {
769
12
  static bool objcGetPropertyDefined = false;
770
12
  static bool objcSetPropertyDefined = false;
771
12
  SourceLocation startLoc = PID->getBeginLoc();
772
12
  InsertText(startLoc, "// ");
773
12
  const char *startBuf = SM->getCharacterData(startLoc);
774
12
  assert((*startBuf == '@') && "bogus @synthesize location");
775
12
  const char *semiBuf = strchr(startBuf, ';');
776
12
  assert((*semiBuf == ';') && "@synthesize: can't find ';'");
777
12
  SourceLocation onePastSemiLoc =
778
12
    startLoc.getLocWithOffset(semiBuf-startBuf+1);
779
12
780
12
  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781
2
    return; // FIXME: is this correct?
782
10
783
10
  // Generate the 'getter' function.
784
10
  ObjCPropertyDecl *PD = PID->getPropertyDecl();
785
10
  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
786
10
787
10
  if (!OID)
788
0
    return;
789
10
  unsigned Attributes = PD->getPropertyAttributes();
790
10
  if (!PD->getGetterMethodDecl()->isDefined()) {
791
9
    bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792
9
                          (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793
9
                                         ObjCPropertyDecl::OBJC_PR_copy));
794
9
    std::string Getr;
795
9
    if (GenGetProperty && 
!objcGetPropertyDefined7
) {
796
5
      objcGetPropertyDefined = true;
797
5
      // FIXME. Is this attribute correct in all cases?
798
5
      Getr = "\nextern \"C\" __declspec(dllimport) "
799
5
            "id objc_getProperty(id, SEL, long, bool);\n";
800
5
    }
801
9
    RewriteObjCMethodDecl(OID->getContainingInterface(),
802
9
                          PD->getGetterMethodDecl(), Getr);
803
9
    Getr += "{ ";
804
9
    // Synthesize an explicit cast to gain access to the ivar.
805
9
    // See objc-act.c:objc_synthesize_new_getter() for details.
806
9
    if (GenGetProperty) {
807
7
      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808
7
      Getr += "typedef ";
809
7
      const FunctionType *FPRetType = nullptr;
810
7
      RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
811
7
                            FPRetType);
812
7
      Getr += " _TYPE";
813
7
      if (FPRetType) {
814
1
        Getr += ")"; // close the precedence "scope" for "*".
815
1
816
1
        // Now, emit the argument types (if any).
817
1
        if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818
1
          Getr += "(";
819
1
          for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
820
0
            if (i) Getr += ", ";
821
0
            std::string ParamStr =
822
0
                FT->getParamType(i).getAsString(Context->getPrintingPolicy());
823
0
            Getr += ParamStr;
824
0
          }
825
1
          if (FT->isVariadic()) {
826
0
            if (FT->getNumParams())
827
0
              Getr += ", ";
828
0
            Getr += "...";
829
0
          }
830
1
          Getr += ")";
831
1
        } else
832
0
          Getr += "()";
833
1
      }
834
7
      Getr += ";\n";
835
7
      Getr += "return (_TYPE)";
836
7
      Getr += "objc_getProperty(self, _cmd, ";
837
7
      RewriteIvarOffsetComputation(OID, Getr);
838
7
      Getr += ", 1)";
839
7
    }
840
2
    else
841
2
      Getr += "return " + getIvarAccessString(OID);
842
9
    Getr += "; }";
843
9
    InsertText(onePastSemiLoc, Getr);
844
9
  }
845
10
846
10
  if (PD->isReadOnly() || 
PD->getSetterMethodDecl()->isDefined()9
)
847
2
    return;
848
8
849
8
  // Generate the 'setter' function.
850
8
  std::string Setr;
851
8
  bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852
8
                                      ObjCPropertyDecl::OBJC_PR_copy);
853
8
  if (GenSetProperty && 
!objcSetPropertyDefined7
) {
854
5
    objcSetPropertyDefined = true;
855
5
    // FIXME. Is this attribute correct in all cases?
856
5
    Setr = "\nextern \"C\" __declspec(dllimport) "
857
5
    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858
5
  }
859
8
860
8
  RewriteObjCMethodDecl(OID->getContainingInterface(),
861
8
                        PD->getSetterMethodDecl(), Setr);
862
8
  Setr += "{ ";
863
8
  // Synthesize an explicit cast to initialize the ivar.
864
8
  // See objc-act.c:objc_synthesize_new_setter() for details.
865
8
  if (GenSetProperty) {
866
7
    Setr += "objc_setProperty (self, _cmd, ";
867
7
    RewriteIvarOffsetComputation(OID, Setr);
868
7
    Setr += ", (id)";
869
7
    Setr += PD->getName();
870
7
    Setr += ", ";
871
7
    if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
872
0
      Setr += "0, ";
873
7
    else
874
7
      Setr += "1, ";
875
7
    if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
876
3
      Setr += "1)";
877
4
    else
878
4
      Setr += "0)";
879
7
  }
880
1
  else {
881
1
    Setr += getIvarAccessString(OID) + " = ";
882
1
    Setr += PD->getName();
883
1
  }
884
8
  Setr += "; }";
885
8
  InsertText(onePastSemiLoc, Setr);
886
8
}
887
888
static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889
27
                                       std::string &typedefString) {
890
27
  typedefString += "#ifndef _REWRITER_typedef_";
891
27
  typedefString += ForwardDecl->getNameAsString();
892
27
  typedefString += "\n";
893
27
  typedefString += "#define _REWRITER_typedef_";
894
27
  typedefString += ForwardDecl->getNameAsString();
895
27
  typedefString += "\n";
896
27
  typedefString += "typedef struct objc_object ";
897
27
  typedefString += ForwardDecl->getNameAsString();
898
27
  typedefString += ";\n#endif\n";
899
27
}
900
901
void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
902
17
                                              const std::string &typedefString) {
903
17
  SourceLocation startLoc = ClassDecl->getBeginLoc();
904
17
  const char *startBuf = SM->getCharacterData(startLoc);
905
17
  const char *semiPtr = strchr(startBuf, ';');
906
17
  // Replace the @class with typedefs corresponding to the classes.
907
17
  ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
908
17
}
909
910
17
void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
911
17
  std::string typedefString;
912
44
  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I27
) {
913
27
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
914
27
    if (I == D.begin()) {
915
17
      // Translate to typedef's that forward reference structs with the same name
916
17
      // as the class. As a convenience, we include the original declaration
917
17
      // as a comment.
918
17
      typedefString += "// @class ";
919
17
      typedefString += ForwardDecl->getNameAsString();
920
17
      typedefString += ";\n";
921
17
    }
922
27
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
923
27
  }
924
17
  DeclGroupRef::iterator I = D.begin();
925
17
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
926
17
}
927
928
0
void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
929
0
  std::string typedefString;
930
0
  for (unsigned i = 0; i < D.size(); i++) {
931
0
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
932
0
    if (i == 0) {
933
0
      typedefString += "// @class ";
934
0
      typedefString += ForwardDecl->getNameAsString();
935
0
      typedefString += ";\n";
936
0
    }
937
0
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
938
0
  }
939
0
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
940
0
}
941
942
123
void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
943
123
  // When method is a synthesized one, such as a getter/setter there is
944
123
  // nothing to rewrite.
945
123
  if (Method->isImplicit())
946
42
    return;
947
81
  SourceLocation LocStart = Method->getBeginLoc();
948
81
  SourceLocation LocEnd = Method->getEndLoc();
949
81
950
81
  if (SM->getExpansionLineNumber(LocEnd) >
951
81
      SM->getExpansionLineNumber(LocStart)) {
952
0
    InsertText(LocStart, "#if 0\n");
953
0
    ReplaceText(LocEnd, 1, ";\n#endif\n");
954
81
  } else {
955
81
    InsertText(LocStart, "// ");
956
81
  }
957
81
}
958
959
23
void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
960
23
  SourceLocation Loc = prop->getAtLoc();
961
23
962
23
  ReplaceText(Loc, 0, "// ");
963
23
  // FIXME: handle properties that are declared across multiple lines.
964
23
}
965
966
6
void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
967
6
  SourceLocation LocStart = CatDecl->getBeginLoc();
968
6
969
6
  // FIXME: handle category headers that are declared across multiple lines.
970
6
  ReplaceText(LocStart, 0, "// ");
971
6
972
6
  for (auto *I : CatDecl->instance_properties())
973
1
    RewriteProperty(I);
974
6
  for (auto *I : CatDecl->instance_methods())
975
6
    RewriteMethodDeclaration(I);
976
6
  for (auto *I : CatDecl->class_methods())
977
0
    RewriteMethodDeclaration(I);
978
6
979
6
  // Lastly, comment out the @end.
980
6
  ReplaceText(CatDecl->getAtEndRange().getBegin(),
981
6
              strlen("@end"), "/* @end */");
982
6
}
983
984
21
void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
985
21
  SourceLocation LocStart = PDecl->getBeginLoc();
986
21
  assert(PDecl->isThisDeclarationADefinition());
987
21
988
21
  // FIXME: handle protocol headers that are declared across multiple lines.
989
21
  ReplaceText(LocStart, 0, "// ");
990
21
991
21
  for (auto *I : PDecl->instance_methods())
992
13
    RewriteMethodDeclaration(I);
993
21
  for (auto *I : PDecl->class_methods())
994
1
    RewriteMethodDeclaration(I);
995
21
  for (auto *I : PDecl->instance_properties())
996
2
    RewriteProperty(I);
997
21
998
21
  // Lastly, comment out the @end.
999
21
  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1000
21
  ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1001
21
1002
21
  // Must comment out @optional/@required
1003
21
  const char *startBuf = SM->getCharacterData(LocStart);
1004
21
  const char *endBuf = SM->getCharacterData(LocEnd);
1005
998
  for (const char *p = startBuf; p < endBuf; 
p++977
) {
1006
977
    if (*p == '@' && 
!strncmp(p+1, "optional", strlen("optional"))25
) {
1007
2
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1008
2
      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1009
2
1010
2
    }
1011
975
    else if (*p == '@' && 
!strncmp(p+1, "required", strlen("required"))23
) {
1012
0
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1013
0
      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1014
0
1015
0
    }
1016
977
  }
1017
21
}
1018
1019
6
void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1020
6
  SourceLocation LocStart = (*D.begin())->getBeginLoc();
1021
6
  if (LocStart.isInvalid())
1022
6
    
llvm_unreachable0
("Invalid SourceLocation");
1023
6
  // FIXME: handle forward protocol that are declared across multiple lines.
1024
6
  ReplaceText(LocStart, 0, "// ");
1025
6
}
1026
1027
void
1028
0
RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1029
0
  SourceLocation LocStart = DG[0]->getBeginLoc();
1030
0
  if (LocStart.isInvalid())
1031
0
    llvm_unreachable("Invalid SourceLocation");
1032
0
  // FIXME: handle forward protocol that are declared across multiple lines.
1033
0
  ReplaceText(LocStart, 0, "// ");
1034
0
}
1035
1036
void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1037
101
                                        const FunctionType *&FPRetType) {
1038
101
  if (T->isObjCQualifiedIdType())
1039
2
    ResultStr += "id";
1040
99
  else if (T->isFunctionPointerType() ||
1041
99
           T->isBlockPointerType()) {
1042
3
    // needs special handling, since pointer-to-functions have special
1043
3
    // syntax (where a decaration models use).
1044
3
    QualType retType = T;
1045
3
    QualType PointeeTy;
1046
3
    if (const PointerType* PT = retType->getAs<PointerType>())
1047
0
      PointeeTy = PT->getPointeeType();
1048
3
    else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1049
3
      PointeeTy = BPT->getPointeeType();
1050
3
    if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1051
3
      ResultStr +=
1052
3
          FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1053
3
      ResultStr += "(*";
1054
3
    }
1055
3
  } else
1056
96
    ResultStr += T.getAsString(Context->getPrintingPolicy());
1057
101
}
1058
1059
void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1060
                                        ObjCMethodDecl *OMD,
1061
94
                                        std::string &ResultStr) {
1062
94
  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1063
94
  const FunctionType *FPRetType = nullptr;
1064
94
  ResultStr += "\nstatic ";
1065
94
  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1066
94
  ResultStr += " ";
1067
94
1068
94
  // Unique method name
1069
94
  std::string NameStr;
1070
94
1071
94
  if (OMD->isInstanceMethod())
1072
88
    NameStr += "_I_";
1073
6
  else
1074
6
    NameStr += "_C_";
1075
94
1076
94
  NameStr += IDecl->getNameAsString();
1077
94
  NameStr += "_";
1078
94
1079
94
  if (ObjCCategoryImplDecl *CID =
1080
6
      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1081
6
    NameStr += CID->getNameAsString();
1082
6
    NameStr += "_";
1083
6
  }
1084
94
  // Append selector names, replacing ':' with '_'
1085
94
  {
1086
94
    std::string selString = OMD->getSelector().getAsString();
1087
94
    int len = selString.size();
1088
1.11k
    for (int i = 0; i < len; 
i++1.02k
)
1089
1.02k
      if (selString[i] == ':')
1090
47
        selString[i] = '_';
1091
94
    NameStr += selString;
1092
94
  }
1093
94
  // Remember this name for metadata emission
1094
94
  MethodInternalNames[OMD] = NameStr;
1095
94
  ResultStr += NameStr;
1096
94
1097
94
  // Rewrite arguments
1098
94
  ResultStr += "(";
1099
94
1100
94
  // invisible arguments
1101
94
  if (OMD->isInstanceMethod()) {
1102
88
    QualType selfTy = Context->getObjCInterfaceType(IDecl);
1103
88
    selfTy = Context->getPointerType(selfTy);
1104
88
    if (!LangOpts.MicrosoftExt) {
1105
30
      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1106
8
        ResultStr += "struct ";
1107
30
    }
1108
88
    // When rewriting for Microsoft, explicitly omit the structure name.
1109
88
    ResultStr += IDecl->getNameAsString();
1110
88
    ResultStr += " *";
1111
88
  }
1112
6
  else
1113
6
    ResultStr += Context->getObjCClassType().getAsString(
1114
6
      Context->getPrintingPolicy());
1115
94
1116
94
  ResultStr += " self, ";
1117
94
  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1118
94
  ResultStr += " _cmd";
1119
94
1120
94
  // Method arguments.
1121
94
  for (const auto *PDecl : OMD->parameters()) {
1122
47
    ResultStr += ", ";
1123
47
    if (PDecl->getType()->isObjCQualifiedIdType()) {
1124
1
      ResultStr += "id ";
1125
1
      ResultStr += PDecl->getNameAsString();
1126
46
    } else {
1127
46
      std::string Name = PDecl->getNameAsString();
1128
46
      QualType QT = PDecl->getType();
1129
46
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
1130
46
      (void)convertBlockPointerToFunctionPointer(QT);
1131
46
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1132
46
      ResultStr += Name;
1133
46
    }
1134
47
  }
1135
94
  if (OMD->isVariadic())
1136
1
    ResultStr += ", ...";
1137
94
  ResultStr += ") ";
1138
94
1139
94
  if (FPRetType) {
1140
2
    ResultStr += ")"; // close the precedence "scope" for "*".
1141
2
1142
2
    // Now, emit the argument types (if any).
1143
2
    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1144
2
      ResultStr += "(";
1145
2
      for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
1146
0
        if (i) ResultStr += ", ";
1147
0
        std::string ParamStr =
1148
0
            FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1149
0
        ResultStr += ParamStr;
1150
0
      }
1151
2
      if (FT->isVariadic()) {
1152
0
        if (FT->getNumParams())
1153
0
          ResultStr += ", ";
1154
0
        ResultStr += "...";
1155
0
      }
1156
2
      ResultStr += ")";
1157
2
    } else {
1158
0
      ResultStr += "()";
1159
0
    }
1160
2
  }
1161
94
}
1162
1163
70
void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1164
70
  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1165
70
  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1166
70
1167
70
  InsertText(IMD ? 
IMD->getBeginLoc()64
:
CID->getBeginLoc()6
, "// ");
1168
70
1169
71
  for (auto *OMD : IMD ? 
IMD->instance_methods()64
:
CID->instance_methods()6
) {
1170
71
    std::string ResultStr;
1171
71
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1172
71
    SourceLocation LocStart = OMD->getBeginLoc();
1173
71
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1174
71
1175
71
    const char *startBuf = SM->getCharacterData(LocStart);
1176
71
    const char *endBuf = SM->getCharacterData(LocEnd);
1177
71
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1178
71
  }
1179
70
1180
70
  for (auto *OMD : IMD ? 
IMD->class_methods()64
:
CID->class_methods()6
) {
1181
6
    std::string ResultStr;
1182
6
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1183
6
    SourceLocation LocStart = OMD->getBeginLoc();
1184
6
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1185
6
1186
6
    const char *startBuf = SM->getCharacterData(LocStart);
1187
6
    const char *endBuf = SM->getCharacterData(LocEnd);
1188
6
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1189
6
  }
1190
70
  for (auto *I : IMD ? 
IMD->property_impls()64
:
CID->property_impls()6
)
1191
12
    RewritePropertyImplDecl(I, IMD, CID);
1192
70
1193
70
  InsertText(IMD ? 
IMD->getEndLoc()64
:
CID->getEndLoc()6
, "// ");
1194
70
}
1195
1196
118
void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1197
118
  std::string ResultStr;
1198
118
  if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1199
118
    // we haven't seen a forward decl - generate a typedef.
1200
118
    ResultStr = "#ifndef _REWRITER_typedef_";
1201
118
    ResultStr += ClassDecl->getNameAsString();
1202
118
    ResultStr += "\n";
1203
118
    ResultStr += "#define _REWRITER_typedef_";
1204
118
    ResultStr += ClassDecl->getNameAsString();
1205
118
    ResultStr += "\n";
1206
118
    ResultStr += "typedef struct objc_object ";
1207
118
    ResultStr += ClassDecl->getNameAsString();
1208
118
    ResultStr += ";\n#endif\n";
1209
118
    // Mark this typedef as having been generated.
1210
118
    ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1211
118
  }
1212
118
  RewriteObjCInternalStruct(ClassDecl, ResultStr);
1213
118
1214
118
  for (auto *I : ClassDecl->instance_properties())
1215
20
    RewriteProperty(I);
1216
118
  for (auto *I : ClassDecl->instance_methods())
1217
92
    RewriteMethodDeclaration(I);
1218
118
  for (auto *I : ClassDecl->class_methods())
1219
11
    RewriteMethodDeclaration(I);
1220
118
1221
118
  // Lastly, comment out the @end.
1222
118
  ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1223
118
              "/* @end */");
1224
118
}
1225
1226
14
Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1227
14
  SourceRange OldRange = PseudoOp->getSourceRange();
1228
14
1229
14
  // We just magically know some things about the structure of this
1230
14
  // expression.
1231
14
  ObjCMessageExpr *OldMsg =
1232
14
    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1233
14
                            PseudoOp->getNumSemanticExprs() - 1));
1234
14
1235
14
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1236
14
  // we need to suppress rewriting the sub-statements.
1237
14
  Expr *Base, *RHS;
1238
14
  {
1239
14
    DisableReplaceStmtScope S(*this);
1240
14
1241
14
    // Rebuild the base expression if we have one.
1242
14
    Base = nullptr;
1243
14
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1244
14
      Base = OldMsg->getInstanceReceiver();
1245
14
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1246
14
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1247
14
    }
1248
14
1249
14
    // Rebuild the RHS.
1250
14
    RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1251
14
    RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1252
14
    RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1253
14
  }
1254
14
1255
14
  // TODO: avoid this copy.
1256
14
  SmallVector<SourceLocation, 1> SelLocs;
1257
14
  OldMsg->getSelectorLocs(SelLocs);
1258
14
1259
14
  ObjCMessageExpr *NewMsg = nullptr;
1260
14
  switch (OldMsg->getReceiverKind()) {
1261
14
  case ObjCMessageExpr::Class:
1262
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1263
0
                                     OldMsg->getValueKind(),
1264
0
                                     OldMsg->getLeftLoc(),
1265
0
                                     OldMsg->getClassReceiverTypeInfo(),
1266
0
                                     OldMsg->getSelector(),
1267
0
                                     SelLocs,
1268
0
                                     OldMsg->getMethodDecl(),
1269
0
                                     RHS,
1270
0
                                     OldMsg->getRightLoc(),
1271
0
                                     OldMsg->isImplicit());
1272
0
    break;
1273
14
1274
14
  case ObjCMessageExpr::Instance:
1275
14
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1276
14
                                     OldMsg->getValueKind(),
1277
14
                                     OldMsg->getLeftLoc(),
1278
14
                                     Base,
1279
14
                                     OldMsg->getSelector(),
1280
14
                                     SelLocs,
1281
14
                                     OldMsg->getMethodDecl(),
1282
14
                                     RHS,
1283
14
                                     OldMsg->getRightLoc(),
1284
14
                                     OldMsg->isImplicit());
1285
14
    break;
1286
14
1287
14
  case ObjCMessageExpr::SuperClass:
1288
0
  case ObjCMessageExpr::SuperInstance:
1289
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1290
0
                                     OldMsg->getValueKind(),
1291
0
                                     OldMsg->getLeftLoc(),
1292
0
                                     OldMsg->getSuperLoc(),
1293
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1294
0
                                     OldMsg->getSuperType(),
1295
0
                                     OldMsg->getSelector(),
1296
0
                                     SelLocs,
1297
0
                                     OldMsg->getMethodDecl(),
1298
0
                                     RHS,
1299
0
                                     OldMsg->getRightLoc(),
1300
0
                                     OldMsg->isImplicit());
1301
0
    break;
1302
14
  }
1303
14
1304
14
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1305
14
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1306
14
  return Replacement;
1307
14
}
1308
1309
22
Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1310
22
  SourceRange OldRange = PseudoOp->getSourceRange();
1311
22
1312
22
  // We just magically know some things about the structure of this
1313
22
  // expression.
1314
22
  ObjCMessageExpr *OldMsg =
1315
22
    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1316
22
1317
22
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1318
22
  // we need to suppress rewriting the sub-statements.
1319
22
  Expr *Base = nullptr;
1320
22
  {
1321
22
    DisableReplaceStmtScope S(*this);
1322
22
1323
22
    // Rebuild the base expression if we have one.
1324
22
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1325
22
      Base = OldMsg->getInstanceReceiver();
1326
22
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1327
22
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1328
22
    }
1329
22
  }
1330
22
1331
22
  // Intentionally empty.
1332
22
  SmallVector<SourceLocation, 1> SelLocs;
1333
22
  SmallVector<Expr*, 1> Args;
1334
22
1335
22
  ObjCMessageExpr *NewMsg = nullptr;
1336
22
  switch (OldMsg->getReceiverKind()) {
1337
22
  case ObjCMessageExpr::Class:
1338
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1339
0
                                     OldMsg->getValueKind(),
1340
0
                                     OldMsg->getLeftLoc(),
1341
0
                                     OldMsg->getClassReceiverTypeInfo(),
1342
0
                                     OldMsg->getSelector(),
1343
0
                                     SelLocs,
1344
0
                                     OldMsg->getMethodDecl(),
1345
0
                                     Args,
1346
0
                                     OldMsg->getRightLoc(),
1347
0
                                     OldMsg->isImplicit());
1348
0
    break;
1349
22
1350
22
  case ObjCMessageExpr::Instance:
1351
22
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1352
22
                                     OldMsg->getValueKind(),
1353
22
                                     OldMsg->getLeftLoc(),
1354
22
                                     Base,
1355
22
                                     OldMsg->getSelector(),
1356
22
                                     SelLocs,
1357
22
                                     OldMsg->getMethodDecl(),
1358
22
                                     Args,
1359
22
                                     OldMsg->getRightLoc(),
1360
22
                                     OldMsg->isImplicit());
1361
22
    break;
1362
22
1363
22
  case ObjCMessageExpr::SuperClass:
1364
0
  case ObjCMessageExpr::SuperInstance:
1365
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366
0
                                     OldMsg->getValueKind(),
1367
0
                                     OldMsg->getLeftLoc(),
1368
0
                                     OldMsg->getSuperLoc(),
1369
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1370
0
                                     OldMsg->getSuperType(),
1371
0
                                     OldMsg->getSelector(),
1372
0
                                     SelLocs,
1373
0
                                     OldMsg->getMethodDecl(),
1374
0
                                     Args,
1375
0
                                     OldMsg->getRightLoc(),
1376
0
                                     OldMsg->isImplicit());
1377
0
    break;
1378
22
  }
1379
22
1380
22
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1381
22
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1382
22
  return Replacement;
1383
22
}
1384
1385
/// SynthCountByEnumWithState - To print:
1386
/// ((unsigned int (*)
1387
///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1388
///  (void *)objc_msgSend)((id)l_collection,
1389
///                        sel_registerName(
1390
///                          "countByEnumeratingWithState:objects:count:"),
1391
///                        &enumState,
1392
///                        (id *)__rw_items, (unsigned int)16)
1393
///
1394
36
void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1395
36
  buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1396
36
  "id *, unsigned int))(void *)objc_msgSend)";
1397
36
  buf += "\n\t\t";
1398
36
  buf += "((id)l_collection,\n\t\t";
1399
36
  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1400
36
  buf += "\n\t\t";
1401
36
  buf += "&enumState, "
1402
36
         "(id *)__rw_items, (unsigned int)16)";
1403
36
}
1404
1405
/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1406
/// statement to exit to its outer synthesized loop.
1407
///
1408
6
Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1409
6
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1410
4
    return S;
1411
2
  // replace break with goto __break_label
1412
2
  std::string buf;
1413
2
1414
2
  SourceLocation startLoc = S->getBeginLoc();
1415
2
  buf = "goto __break_label_";
1416
2
  buf += utostr(ObjCBcLabelNo.back());
1417
2
  ReplaceText(startLoc, strlen("break"), buf);
1418
2
1419
2
  return nullptr;
1420
2
}
1421
1422
/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1423
/// statement to continue with its inner synthesized loop.
1424
///
1425
2
Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1426
2
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1427
0
    return S;
1428
2
  // replace continue with goto __continue_label
1429
2
  std::string buf;
1430
2
1431
2
  SourceLocation startLoc = S->getBeginLoc();
1432
2
  buf = "goto __continue_label_";
1433
2
  buf += utostr(ObjCBcLabelNo.back());
1434
2
  ReplaceText(startLoc, strlen("continue"), buf);
1435
2
1436
2
  return nullptr;
1437
2
}
1438
1439
/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1440
///  It rewrites:
1441
/// for ( type elem in collection) { stmts; }
1442
1443
/// Into:
1444
/// {
1445
///   type elem;
1446
///   struct __objcFastEnumerationState enumState = { 0 };
1447
///   id __rw_items[16];
1448
///   id l_collection = (id)collection;
1449
///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1450
///                                       objects:__rw_items count:16];
1451
/// if (limit) {
1452
///   unsigned long startMutations = *enumState.mutationsPtr;
1453
///   do {
1454
///        unsigned long counter = 0;
1455
///        do {
1456
///             if (startMutations != *enumState.mutationsPtr)
1457
///               objc_enumerationMutation(l_collection);
1458
///             elem = (type)enumState.itemsPtr[counter++];
1459
///             stmts;
1460
///             __continue_label: ;
1461
///        } while (counter < limit);
1462
///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1463
///                                  objects:__rw_items count:16]);
1464
///   elem = nil;
1465
///   __break_label: ;
1466
///  }
1467
///  else
1468
///       elem = nil;
1469
///  }
1470
///
1471
Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1472
18
                                                SourceLocation OrigEnd) {
1473
18
  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1474
18
  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1475
18
         "ObjCForCollectionStmt Statement stack mismatch");
1476
18
  assert(!ObjCBcLabelNo.empty() &&
1477
18
         "ObjCForCollectionStmt - Label No stack empty");
1478
18
1479
18
  SourceLocation startLoc = S->getBeginLoc();
1480
18
  const char *startBuf = SM->getCharacterData(startLoc);
1481
18
  StringRef elementName;
1482
18
  std::string elementTypeAsString;
1483
18
  std::string buf;
1484
18
  buf = "\n{\n\t";
1485
18
  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1486
9
    // type elem;
1487
9
    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1488
9
    QualType ElementType = cast<ValueDecl>(D)->getType();
1489
9
    if (ElementType->isObjCQualifiedIdType() ||
1490
9
        
ElementType->isObjCQualifiedInterfaceType()8
)
1491
1
      // Simply use 'id' for all qualified types.
1492
1
      elementTypeAsString = "id";
1493
8
    else
1494
8
      elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1495
9
    buf += elementTypeAsString;
1496
9
    buf += " ";
1497
9
    elementName = D->getName();
1498
9
    buf += elementName;
1499
9
    buf += ";\n\t";
1500
9
  }
1501
9
  else {
1502
9
    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1503
9
    elementName = DR->getDecl()->getName();
1504
9
    ValueDecl *VD = DR->getDecl();
1505
9
    if (VD->getType()->isObjCQualifiedIdType() ||
1506
9
        VD->getType()->isObjCQualifiedInterfaceType())
1507
0
      // Simply use 'id' for all qualified types.
1508
0
      elementTypeAsString = "id";
1509
9
    else
1510
9
      elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1511
9
  }
1512
18
1513
18
  // struct __objcFastEnumerationState enumState = { 0 };
1514
18
  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1515
18
  // id __rw_items[16];
1516
18
  buf += "id __rw_items[16];\n\t";
1517
18
  // id l_collection = (id)
1518
18
  buf += "id l_collection = (id)";
1519
18
  // Find start location of 'collection' the hard way!
1520
18
  const char *startCollectionBuf = startBuf;
1521
18
  startCollectionBuf += 3;  // skip 'for'
1522
18
  startCollectionBuf = strchr(startCollectionBuf, '(');
1523
18
  startCollectionBuf++; // skip '('
1524
18
  // find 'in' and skip it.
1525
151
  while (*startCollectionBuf != ' ' ||
1526
151
         
*(startCollectionBuf+1) != 'i'29
||
*(startCollectionBuf+2) != 'n'18
||
1527
151
         
(18
*(startCollectionBuf+3) != ' '18
&&
1528
18
          
*(startCollectionBuf+3) != '['3
&&
*(startCollectionBuf+3) != '('1
))
1529
133
    startCollectionBuf++;
1530
18
  startCollectionBuf += 3;
1531
18
1532
18
  // Replace: "for (type element in" with string constructed thus far.
1533
18
  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1534
18
  // Replace ')' in for '(' type elem in collection ')' with ';'
1535
18
  SourceLocation rightParenLoc = S->getRParenLoc();
1536
18
  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1537
18
  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1538
18
  buf = ";\n\t";
1539
18
1540
18
  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1541
18
  //                                   objects:__rw_items count:16];
1542
18
  // which is synthesized into:
1543
18
  // unsigned int limit =
1544
18
  // ((unsigned int (*)
1545
18
  //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1546
18
  //  (void *)objc_msgSend)((id)l_collection,
1547
18
  //                        sel_registerName(
1548
18
  //                          "countByEnumeratingWithState:objects:count:"),
1549
18
  //                        (struct __objcFastEnumerationState *)&state,
1550
18
  //                        (id *)__rw_items, (unsigned int)16);
1551
18
  buf += "unsigned long limit =\n\t\t";
1552
18
  SynthCountByEnumWithState(buf);
1553
18
  buf += ";\n\t";
1554
18
  /// if (limit) {
1555
18
  ///   unsigned long startMutations = *enumState.mutationsPtr;
1556
18
  ///   do {
1557
18
  ///        unsigned long counter = 0;
1558
18
  ///        do {
1559
18
  ///             if (startMutations != *enumState.mutationsPtr)
1560
18
  ///               objc_enumerationMutation(l_collection);
1561
18
  ///             elem = (type)enumState.itemsPtr[counter++];
1562
18
  buf += "if (limit) {\n\t";
1563
18
  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1564
18
  buf += "do {\n\t\t";
1565
18
  buf += "unsigned long counter = 0;\n\t\t";
1566
18
  buf += "do {\n\t\t\t";
1567
18
  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1568
18
  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1569
18
  buf += elementName;
1570
18
  buf += " = (";
1571
18
  buf += elementTypeAsString;
1572
18
  buf += ")enumState.itemsPtr[counter++];";
1573
18
  // Replace ')' in for '(' type elem in collection ')' with all of these.
1574
18
  ReplaceText(lparenLoc, 1, buf);
1575
18
1576
18
  ///            __continue_label: ;
1577
18
  ///        } while (counter < limit);
1578
18
  ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1579
18
  ///                                  objects:__rw_items count:16]);
1580
18
  ///   elem = nil;
1581
18
  ///   __break_label: ;
1582
18
  ///  }
1583
18
  ///  else
1584
18
  ///       elem = nil;
1585
18
  ///  }
1586
18
  ///
1587
18
  buf = ";\n\t";
1588
18
  buf += "__continue_label_";
1589
18
  buf += utostr(ObjCBcLabelNo.back());
1590
18
  buf += ": ;";
1591
18
  buf += "\n\t\t";
1592
18
  buf += "} while (counter < limit);\n\t";
1593
18
  buf += "} while (limit = ";
1594
18
  SynthCountByEnumWithState(buf);
1595
18
  buf += ");\n\t";
1596
18
  buf += elementName;
1597
18
  buf += " = ((";
1598
18
  buf += elementTypeAsString;
1599
18
  buf += ")0);\n\t";
1600
18
  buf += "__break_label_";
1601
18
  buf += utostr(ObjCBcLabelNo.back());
1602
18
  buf += ": ;\n\t";
1603
18
  buf += "}\n\t";
1604
18
  buf += "else\n\t\t";
1605
18
  buf += elementName;
1606
18
  buf += " = ((";
1607
18
  buf += elementTypeAsString;
1608
18
  buf += ")0);\n\t";
1609
18
  buf += "}\n";
1610
18
1611
18
  // Insert all these *after* the statement body.
1612
18
  // FIXME: If this should support Obj-C++, support CXXTryStmt
1613
18
  if (isa<CompoundStmt>(S->getBody())) {
1614
12
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1615
12
    InsertText(endBodyLoc, buf);
1616
12
  } else {
1617
6
    /* Need to treat single statements specially. For example:
1618
6
     *
1619
6
     *     for (A *a in b) if (stuff()) break;
1620
6
     *     for (A *a in b) xxxyy;
1621
6
     *
1622
6
     * The following code simply scans ahead to the semi to find the actual end.
1623
6
     */
1624
6
    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1625
6
    const char *semiBuf = strchr(stmtBuf, ';');
1626
6
    assert(semiBuf && "Can't find ';'");
1627
6
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1628
6
    InsertText(endBodyLoc, buf);
1629
6
  }
1630
18
  Stmts.pop_back();
1631
18
  ObjCBcLabelNo.pop_back();
1632
18
  return nullptr;
1633
18
}
1634
1635
/// RewriteObjCSynchronizedStmt -
1636
/// This routine rewrites @synchronized(expr) stmt;
1637
/// into:
1638
/// objc_sync_enter(expr);
1639
/// @try stmt @finally { objc_sync_exit(expr); }
1640
///
1641
3
Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1642
3
  // Get the start location and compute the semi location.
1643
3
  SourceLocation startLoc = S->getBeginLoc();
1644
3
  const char *startBuf = SM->getCharacterData(startLoc);
1645
3
1646
3
  assert((*startBuf == '@') && "bogus @synchronized location");
1647
3
1648
3
  std::string buf;
1649
3
  buf = "objc_sync_enter((id)";
1650
3
  const char *lparenBuf = startBuf;
1651
45
  while (*lparenBuf != '(') 
lparenBuf++42
;
1652
3
  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1653
3
  // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1654
3
  // the sync expression is typically a message expression that's already
1655
3
  // been rewritten! (which implies the SourceLocation's are invalid).
1656
3
  SourceLocation endLoc = S->getSynchBody()->getBeginLoc();
1657
3
  const char *endBuf = SM->getCharacterData(endLoc);
1658
9
  while (*endBuf != ')') 
endBuf--6
;
1659
3
  SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1660
3
  buf = ");\n";
1661
3
  // declare a new scope with two variables, _stack and _rethrow.
1662
3
  buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1663
3
  buf += "int buf[18/*32-bit i386*/];\n";
1664
3
  buf += "char *pointers[4];} _stack;\n";
1665
3
  buf += "id volatile _rethrow = 0;\n";
1666
3
  buf += "objc_exception_try_enter(&_stack);\n";
1667
3
  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1668
3
  ReplaceText(rparenLoc, 1, buf);
1669
3
  startLoc = S->getSynchBody()->getEndLoc();
1670
3
  startBuf = SM->getCharacterData(startLoc);
1671
3
1672
3
  assert((*startBuf == '}') && "bogus @synchronized block");
1673
3
  SourceLocation lastCurlyLoc = startLoc;
1674
3
  buf = "}\nelse {\n";
1675
3
  buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1676
3
  buf += "}\n";
1677
3
  buf += "{ /* implicit finally clause */\n";
1678
3
  buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1679
3
1680
3
  std::string syncBuf;
1681
3
  syncBuf += " objc_sync_exit(";
1682
3
1683
3
  Expr *syncExpr = S->getSynchExpr();
1684
3
  CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1685
3
                  ? CK_BitCast :
1686
3
                syncExpr->getType()->isBlockPointerType()
1687
0
                  ? CK_BlockPointerToObjCPointerCast
1688
0
                  : CK_CPointerToObjCPointerCast;
1689
3
  syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1690
3
                                      CK, syncExpr);
1691
3
  std::string syncExprBufS;
1692
3
  llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1693
3
  assert(syncExpr != nullptr && "Expected non-null Expr");
1694
3
  syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1695
3
  syncBuf += syncExprBuf.str();
1696
3
  syncBuf += ");";
1697
3
1698
3
  buf += syncBuf;
1699
3
  buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1700
3
  buf += "}\n";
1701
3
  buf += "}";
1702
3
1703
3
  ReplaceText(lastCurlyLoc, 1, buf);
1704
3
1705
3
  bool hasReturns = false;
1706
3
  HasReturnStmts(S->getSynchBody(), hasReturns);
1707
3
  if (hasReturns)
1708
3
    RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1709
3
1710
3
  return nullptr;
1711
3
}
1712
1713
void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1714
26
{
1715
26
  // Perform a bottom up traversal of all children.
1716
26
  for (Stmt *SubStmt : S->children())
1717
22
    if (SubStmt)
1718
22
      WarnAboutReturnGotoStmts(SubStmt);
1719
26
1720
26
  if (isa<ReturnStmt>(S) || 
isa<GotoStmt>(S)25
) {
1721
1
    Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1722
1
                 TryFinallyContainsReturnDiag);
1723
1
  }
1724
26
}
1725
1726
void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1727
23
{
1728
23
  // Perform a bottom up traversal of all children.
1729
23
  for (Stmt *SubStmt : S->children())
1730
16
    if (SubStmt)
1731
16
      HasReturnStmts(SubStmt, hasReturns);
1732
23
1733
23
  if (isa<ReturnStmt>(S))
1734
4
    hasReturns = true;
1735
23
}
1736
1737
2
void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1738
2
  // Perform a bottom up traversal of all children.
1739
2
  for (Stmt *SubStmt : S->children())
1740
1
    if (SubStmt) {
1741
1
      RewriteTryReturnStmts(SubStmt);
1742
1
    }
1743
2
  if (isa<ReturnStmt>(S)) {
1744
1
    SourceLocation startLoc = S->getBeginLoc();
1745
1
    const char *startBuf = SM->getCharacterData(startLoc);
1746
1
    const char *semiBuf = strchr(startBuf, ';');
1747
1
    assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1748
1
    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1749
1
1750
1
    std::string buf;
1751
1
    buf = "{ objc_exception_try_exit(&_stack); return";
1752
1
1753
1
    ReplaceText(startLoc, 6, buf);
1754
1
    InsertText(onePastSemiLoc, "}");
1755
1
  }
1756
2
}
1757
1758
12
void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1759
12
  // Perform a bottom up traversal of all children.
1760
12
  for (Stmt *SubStmt : S->children())
1761
9
    if (SubStmt) {
1762
9
      RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1763
9
    }
1764
12
  if (isa<ReturnStmt>(S)) {
1765
3
    SourceLocation startLoc = S->getBeginLoc();
1766
3
    const char *startBuf = SM->getCharacterData(startLoc);
1767
3
1768
3
    const char *semiBuf = strchr(startBuf, ';');
1769
3
    assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1770
3
    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1771
3
1772
3
    std::string buf;
1773
3
    buf = "{ objc_exception_try_exit(&_stack);";
1774
3
    buf += syncExitBuf;
1775
3
    buf += " return";
1776
3
1777
3
    ReplaceText(startLoc, 6, buf);
1778
3
    InsertText(onePastSemiLoc, "}");
1779
3
  }
1780
12
}
1781
1782
8
Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1783
8
  // Get the start location and compute the semi location.
1784
8
  SourceLocation startLoc = S->getBeginLoc();
1785
8
  const char *startBuf = SM->getCharacterData(startLoc);
1786
8
1787
8
  assert((*startBuf == '@') && "bogus @try location");
1788
8
1789
8
  std::string buf;
1790
8
  // declare a new scope with two variables, _stack and _rethrow.
1791
8
  buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1792
8
  buf += "int buf[18/*32-bit i386*/];\n";
1793
8
  buf += "char *pointers[4];} _stack;\n";
1794
8
  buf += "id volatile _rethrow = 0;\n";
1795
8
  buf += "objc_exception_try_enter(&_stack);\n";
1796
8
  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1797
8
1798
8
  ReplaceText(startLoc, 4, buf);
1799
8
1800
8
  startLoc = S->getTryBody()->getEndLoc();
1801
8
  startBuf = SM->getCharacterData(startLoc);
1802
8
1803
8
  assert((*startBuf == '}') && "bogus @try block");
1804
8
1805
8
  SourceLocation lastCurlyLoc = startLoc;
1806
8
  if (S->getNumCatchStmts()) {
1807
4
    startLoc = startLoc.getLocWithOffset(1);
1808
4
    buf = " /* @catch begin */ else {\n";
1809
4
    buf += " id _caught = objc_exception_extract(&_stack);\n";
1810
4
    buf += " objc_exception_try_enter (&_stack);\n";
1811
4
    buf += " if (_setjmp(_stack.buf))\n";
1812
4
    buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1813
4
    buf += " else { /* @catch continue */";
1814
4
1815
4
    InsertText(startLoc, buf);
1816
4
  } else { /* no catch list */
1817
4
    buf = "}\nelse {\n";
1818
4
    buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1819
4
    buf += "}";
1820
4
    ReplaceText(lastCurlyLoc, 1, buf);
1821
4
  }
1822
8
  Stmt *lastCatchBody = nullptr;
1823
14
  for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; 
++I6
) {
1824
6
    ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1825
6
    VarDecl *catchDecl = Catch->getCatchParamDecl();
1826
6
1827
6
    if (I == 0)
1828
4
      buf = "if ("; // we are generating code for the first catch clause
1829
2
    else
1830
2
      buf = "else if (";
1831
6
    startLoc = Catch->getBeginLoc();
1832
6
    startBuf = SM->getCharacterData(startLoc);
1833
6
1834
6
    assert((*startBuf == '@') && "bogus @catch location");
1835
6
1836
6
    const char *lParenLoc = strchr(startBuf, '(');
1837
6
1838
6
    if (Catch->hasEllipsis()) {
1839
2
      // Now rewrite the body...
1840
2
      lastCatchBody = Catch->getCatchBody();
1841
2
      SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1842
2
      const char *bodyBuf = SM->getCharacterData(bodyLoc);
1843
2
      assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1844
2
             "bogus @catch paren location");
1845
2
      assert((*bodyBuf == '{') && "bogus @catch body location");
1846
2
1847
2
      buf += "1) { id _tmp = _caught;";
1848
2
      Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1849
4
    } else if (catchDecl) {
1850
4
      QualType t = catchDecl->getType();
1851
4
      if (t == Context->getObjCIdType()) {
1852
1
        buf += "1) { ";
1853
1
        ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1854
3
      } else if (const ObjCObjectPointerType *Ptr =
1855
3
                   t->getAs<ObjCObjectPointerType>()) {
1856
3
        // Should be a pointer to a class.
1857
3
        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1858
3
        if (IDecl) {
1859
3
          buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1860
3
          buf += IDecl->getNameAsString();
1861
3
          buf += "\"), (struct objc_object *)_caught)) { ";
1862
3
          ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1863
3
        }
1864
3
      }
1865
4
      // Now rewrite the body...
1866
4
      lastCatchBody = Catch->getCatchBody();
1867
4
      SourceLocation rParenLoc = Catch->getRParenLoc();
1868
4
      SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1869
4
      const char *bodyBuf = SM->getCharacterData(bodyLoc);
1870
4
      const char *rParenBuf = SM->getCharacterData(rParenLoc);
1871
4
      assert((*rParenBuf == ')') && "bogus @catch paren location");
1872
4
      assert((*bodyBuf == '{') && "bogus @catch body location");
1873
4
1874
4
      // Here we replace ") {" with "= _caught;" (which initializes and
1875
4
      // declares the @catch parameter).
1876
4
      ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1877
4
    } else {
1878
0
      llvm_unreachable("@catch rewrite bug");
1879
0
    }
1880
6
  }
1881
8
  // Complete the catch list...
1882
8
  if (lastCatchBody) {
1883
4
    SourceLocation bodyLoc = lastCatchBody->getEndLoc();
1884
4
    assert(*SM->getCharacterData(bodyLoc) == '}' &&
1885
4
           "bogus @catch body location");
1886
4
1887
4
    // Insert the last (implicit) else clause *before* the right curly brace.
1888
4
    bodyLoc = bodyLoc.getLocWithOffset(-1);
1889
4
    buf = "} /* last catch end */\n";
1890
4
    buf += "else {\n";
1891
4
    buf += " _rethrow = _caught;\n";
1892
4
    buf += " objc_exception_try_exit(&_stack);\n";
1893
4
    buf += "} } /* @catch end */\n";
1894
4
    if (!S->getFinallyStmt())
1895
4
      buf += "}\n";
1896
4
    InsertText(bodyLoc, buf);
1897
4
1898
4
    // Set lastCurlyLoc
1899
4
    lastCurlyLoc = lastCatchBody->getEndLoc();
1900
4
  }
1901
8
  if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1902
4
    startLoc = finalStmt->getBeginLoc();
1903
4
    startBuf = SM->getCharacterData(startLoc);
1904
4
    assert((*startBuf == '@') && "bogus @finally start");
1905
4
1906
4
    ReplaceText(startLoc, 8, "/* @finally */");
1907
4
1908
4
    Stmt *body = finalStmt->getFinallyBody();
1909
4
    SourceLocation startLoc = body->getBeginLoc();
1910
4
    SourceLocation endLoc = body->getEndLoc();
1911
4
    assert(*SM->getCharacterData(startLoc) == '{' &&
1912
4
           "bogus @finally body location");
1913
4
    assert(*SM->getCharacterData(endLoc) == '}' &&
1914
4
           "bogus @finally body location");
1915
4
1916
4
    startLoc = startLoc.getLocWithOffset(1);
1917
4
    InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1918
4
    endLoc = endLoc.getLocWithOffset(-1);
1919
4
    InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1920
4
1921
4
    // Set lastCurlyLoc
1922
4
    lastCurlyLoc = body->getEndLoc();
1923
4
1924
4
    // Now check for any return/continue/go statements within the @try.
1925
4
    WarnAboutReturnGotoStmts(S->getTryBody());
1926
4
  } else { /* no finally clause - make sure we synthesize an implicit one */
1927
4
    buf = "{ /* implicit finally clause */\n";
1928
4
    buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1929
4
    buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1930
4
    buf += "}";
1931
4
    ReplaceText(lastCurlyLoc, 1, buf);
1932
4
1933
4
    // Now check for any return/continue/go statements within the @try.
1934
4
    // The implicit finally clause won't called if the @try contains any
1935
4
    // jump statements.
1936
4
    bool hasReturns = false;
1937
4
    HasReturnStmts(S->getTryBody(), hasReturns);
1938
4
    if (hasReturns)
1939
1
      RewriteTryReturnStmts(S->getTryBody());
1940
4
  }
1941
8
  // Now emit the final closing curly brace...
1942
8
  lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1943
8
  InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1944
8
  return nullptr;
1945
8
}
1946
1947
// This can't be done with ReplaceStmt(S, ThrowExpr), since
1948
// the throw expression is typically a message expression that's already
1949
// been rewritten! (which implies the SourceLocation's are invalid).
1950
2
Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1951
2
  // Get the start location and compute the semi location.
1952
2
  SourceLocation startLoc = S->getBeginLoc();
1953
2
  const char *startBuf = SM->getCharacterData(startLoc);
1954
2
1955
2
  assert((*startBuf == '@') && "bogus @throw location");
1956
2
1957
2
  std::string buf;
1958
2
  /* void objc_exception_throw(id) __attribute__((noreturn)); */
1959
2
  if (S->getThrowExpr())
1960
0
    buf = "objc_exception_throw(";
1961
2
  else // add an implicit argument
1962
2
    buf = "objc_exception_throw(_caught";
1963
2
1964
2
  // handle "@  throw" correctly.
1965
2
  const char *wBuf = strchr(startBuf, 'w');
1966
2
  assert((*wBuf == 'w') && "@throw: can't find 'w'");
1967
2
  ReplaceText(startLoc, wBuf-startBuf+1, buf);
1968
2
1969
2
  const char *semiBuf = strchr(startBuf, ';');
1970
2
  assert((*semiBuf == ';') && "@throw: can't find ';'");
1971
2
  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1972
2
  ReplaceText(semiLoc, 1, ");");
1973
2
  return nullptr;
1974
2
}
1975
1976
3
Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1977
3
  // Create a new string expression.
1978
3
  std::string StrEncoding;
1979
3
  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1980
3
  Expr *Replacement = getStringLiteral(StrEncoding);
1981
3
  ReplaceStmt(Exp, Replacement);
1982
3
1983
3
  // Replace this subexpr in the parent.
1984
3
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1985
3
  return Replacement;
1986
3
}
1987
1988
1
Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1989
1
  if (!SelGetUidFunctionDecl)
1990
1
    SynthSelGetUidFunctionDecl();
1991
1
  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1992
1
  // Create a call to sel_registerName("selName").
1993
1
  SmallVector<Expr*, 8> SelExprs;
1994
1
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
1995
1
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1996
1
                                                  SelExprs);
1997
1
  ReplaceStmt(Exp, SelExp);
1998
1
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1999
1
  return SelExp;
2000
1
}
2001
2002
CallExpr *
2003
RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2004
                                          ArrayRef<Expr *> Args,
2005
                                          SourceLocation StartLoc,
2006
139
                                          SourceLocation EndLoc) {
2007
139
  // Get the type, we will need to reference it in a couple spots.
2008
139
  QualType msgSendType = FD->getType();
2009
139
2010
139
  // Create a reference to the objc_msgSend() declaration.
2011
139
  DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2012
139
                                               VK_LValue, SourceLocation());
2013
139
2014
139
  // Now, we cast the reference to a pointer to the objc_msgSend type.
2015
139
  QualType pToFunc = Context->getPointerType(msgSendType);
2016
139
  ImplicitCastExpr *ICE =
2017
139
    ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2018
139
                             DRE, nullptr, VK_RValue);
2019
139
2020
139
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2021
139
2022
139
  CallExpr *Exp = CallExpr::Create(
2023
139
      *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2024
139
  return Exp;
2025
139
}
2026
2027
static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2028
26
                                const char *&startRef, const char *&endRef) {
2029
360
  while (startBuf < endBuf) {
2030
360
    if (*startBuf == '<')
2031
26
      startRef = startBuf; // mark the start.
2032
360
    if (*startBuf == '>') {
2033
26
      if (startRef && *startRef == '<') {
2034
26
        endRef = startBuf; // mark the end.
2035
26
        return true;
2036
26
      }
2037
0
      return false;
2038
0
    }
2039
334
    startBuf++;
2040
334
  }
2041
26
  
return false0
;
2042
26
}
2043
2044
6
static void scanToNextArgument(const char *&argRef) {
2045
6
  int angle = 0;
2046
147
  while (*argRef != ')' && 
(144
*argRef != ','144
||
angle > 05
)) {
2047
141
    if (*argRef == '<')
2048
6
      angle++;
2049
135
    else if (*argRef == '>')
2050
6
      angle--;
2051
141
    argRef++;
2052
141
  }
2053
6
  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2054
6
}
2055
2056
371
bool RewriteObjC::needToScanForQualifiers(QualType T) {
2057
371
  if (T->isObjCQualifiedIdType())
2058
9
    return true;
2059
362
  if (const PointerType *PT = T->getAs<PointerType>()) {
2060
37
    if (PT->getPointeeType()->isObjCQualifiedIdType())
2061
1
      return true;
2062
361
  }
2063
361
  if (T->isObjCObjectPointerType()) {
2064
113
    T = T->getPointeeType();
2065
113
    return T->isObjCQualifiedInterfaceType();
2066
113
  }
2067
248
  if (T->isArrayType()) {
2068
3
    QualType ElemTy = Context->getBaseElementType(T);
2069
3
    return needToScanForQualifiers(ElemTy);
2070
3
  }
2071
245
  return false;
2072
245
}
2073
2074
31
void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2075
31
  QualType Type = E->getType();
2076
31
  if (needToScanForQualifiers(Type)) {
2077
7
    SourceLocation Loc, EndLoc;
2078
7
2079
7
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2080
7
      Loc = ECE->getLParenLoc();
2081
7
      EndLoc = ECE->getRParenLoc();
2082
7
    } else {
2083
0
      Loc = E->getBeginLoc();
2084
0
      EndLoc = E->getEndLoc();
2085
0
    }
2086
7
    // This will defend against trying to rewrite synthesized expressions.
2087
7
    if (Loc.isInvalid() || EndLoc.isInvalid())
2088
0
      return;
2089
7
2090
7
    const char *startBuf = SM->getCharacterData(Loc);
2091
7
    const char *endBuf = SM->getCharacterData(EndLoc);
2092
7
    const char *startRef = nullptr, *endRef = nullptr;
2093
7
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2094
7
      // Get the locations of the startRef, endRef.
2095
7
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2096
7
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2097
7
      // Comment out the protocol references.
2098
7
      InsertText(LessLoc, "/*");
2099
7
      InsertText(GreaterLoc, "*/");
2100
7
    }
2101
7
  }
2102
31
}
2103
2104
265
void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2105
265
  SourceLocation Loc;
2106
265
  QualType Type;
2107
265
  const FunctionProtoType *proto = nullptr;
2108
265
  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2109
149
    Loc = VD->getLocation();
2110
149
    Type = VD->getType();
2111
149
  }
2112
116
  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2113
115
    Loc = FD->getLocation();
2114
115
    // Check for ObjC 'id' and class types that have been adorned with protocol
2115
115
    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2116
115
    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2117
115
    assert(funcType && "missing function type");
2118
115
    proto = dyn_cast<FunctionProtoType>(funcType);
2119
115
    if (!proto)
2120
23
      return;
2121
92
    Type = proto->getReturnType();
2122
92
  }
2123
1
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2124
1
    Loc = FD->getLocation();
2125
1
    Type = FD->getType();
2126
1
  }
2127
0
  else
2128
0
    return;
2129
242
2130
242
  if (needToScanForQualifiers(Type)) {
2131
13
    // Since types are unique, we need to scan the buffer.
2132
13
2133
13
    const char *endBuf = SM->getCharacterData(Loc);
2134
13
    const char *startBuf = endBuf;
2135
217
    while (*startBuf != ';' && *startBuf != '<' && 
startBuf != MainFileStart204
)
2136
204
      startBuf--; // scan backward (from the decl location) for return type.
2137
13
    const char *startRef = nullptr, *endRef = nullptr;
2138
13
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2139
13
      // Get the locations of the startRef, endRef.
2140
13
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2141
13
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2142
13
      // Comment out the protocol references.
2143
13
      InsertText(LessLoc, "/*");
2144
13
      InsertText(GreaterLoc, "*/");
2145
13
    }
2146
13
  }
2147
242
  if (!proto)
2148
150
      return; // most likely, was a variable
2149
92
  // Now check arguments.
2150
92
  const char *startBuf = SM->getCharacterData(Loc);
2151
92
  const char *startFuncBuf = startBuf;
2152
172
  for (unsigned i = 0; i < proto->getNumParams(); 
i++80
) {
2153
80
    if (needToScanForQualifiers(proto->getParamType(i))) {
2154
6
      // Since types are unique, we need to scan the buffer.
2155
6
2156
6
      const char *endBuf = startBuf;
2157
6
      // scan forward (from the decl location) for argument types.
2158
6
      scanToNextArgument(endBuf);
2159
6
      const char *startRef = nullptr, *endRef = nullptr;
2160
6
      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2161
6
        // Get the locations of the startRef, endRef.
2162
6
        SourceLocation LessLoc =
2163
6
          Loc.getLocWithOffset(startRef-startFuncBuf);
2164
6
        SourceLocation GreaterLoc =
2165
6
          Loc.getLocWithOffset(endRef-startFuncBuf+1);
2166
6
        // Comment out the protocol references.
2167
6
        InsertText(LessLoc, "/*");
2168
6
        InsertText(GreaterLoc, "*/");
2169
6
      }
2170
6
      startBuf = ++endBuf;
2171
6
    }
2172
74
    else {
2173
74
      // If the function name is derived from a macro expansion, then the
2174
74
      // argument buffer will not follow the name. Need to speak with Chris.
2175
1.26k
      while (*startBuf && *startBuf != ')' && 
*startBuf != ','1.20k
)
2176
1.18k
        startBuf++; // scan forward (from the decl location) for argument types.
2177
74
      startBuf++;
2178
74
    }
2179
80
  }
2180
92
}
2181
2182
119
void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2183
119
  QualType QT = ND->getType();
2184
119
  const Type* TypePtr = QT->getAs<Type>();
2185
119
  if (!isa<TypeOfExprType>(TypePtr))
2186
116
    return;
2187
9
  
while (3
isa<TypeOfExprType>(TypePtr)) {
2188
6
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2189
6
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2190
6
    TypePtr = QT->getAs<Type>();
2191
6
  }
2192
3
  // FIXME. This will not work for multiple declarators; as in:
2193
3
  // __typeof__(a) b,c,d;
2194
3
  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2195
3
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2196
3
  const char *startBuf = SM->getCharacterData(DeclLoc);
2197
3
  if (ND->getInit()) {
2198
2
    std::string Name(ND->getNameAsString());
2199
2
    TypeAsString += " " + Name + " = ";
2200
2
    Expr *E = ND->getInit();
2201
2
    SourceLocation startLoc;
2202
2
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2203
0
      startLoc = ECE->getLParenLoc();
2204
2
    else
2205
2
      startLoc = E->getBeginLoc();
2206
2
    startLoc = SM->getExpansionLoc(startLoc);
2207
2
    const char *endBuf = SM->getCharacterData(startLoc);
2208
2
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2209
2
  }
2210
1
  else {
2211
1
    SourceLocation X = ND->getEndLoc();
2212
1
    X = SM->getExpansionLoc(X);
2213
1
    const char *endBuf = SM->getCharacterData(X);
2214
1
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2215
1
  }
2216
3
}
2217
2218
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2219
15
void RewriteObjC::SynthSelGetUidFunctionDecl() {
2220
15
  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2221
15
  SmallVector<QualType, 16> ArgTys;
2222
15
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2223
15
  QualType getFuncType =
2224
15
    getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2225
15
  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2226
15
                                               SourceLocation(),
2227
15
                                               SourceLocation(),
2228
15
                                               SelGetUidIdent, getFuncType,
2229
15
                                               nullptr, SC_Extern);
2230
15
}
2231
2232
136
void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2233
136
  // declared in <objc/objc.h>
2234
136
  if (FD->getIdentifier() &&
2235
136
      FD->getName() == "sel_registerName") {
2236
21
    SelGetUidFunctionDecl = FD;
2237
21
    return;
2238
21
  }
2239
115
  RewriteObjCQualifiedInterfaceTypes(FD);
2240
115
}
2241
2242
13
void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2243
13
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2244
13
  const char *argPtr = TypeString.c_str();
2245
13
  if (!strchr(argPtr, '^')) {
2246
6
    Str += TypeString;
2247
6
    return;
2248
6
  }
2249
105
  
while (7
*argPtr) {
2250
98
    Str += (*argPtr == '^' ? 
'*'7
:
*argPtr91
);
2251
98
    argPtr++;
2252
98
  }
2253
7
}
2254
2255
// FIXME. Consolidate this routine with RewriteBlockPointerType.
2256
void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2257
2
                                                  ValueDecl *VD) {
2258
2
  QualType Type = VD->getType();
2259
2
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2260
2
  const char *argPtr = TypeString.c_str();
2261
2
  int paren = 0;
2262
29
  while (*argPtr) {
2263
27
    switch (*argPtr) {
2264
27
      case '(':
2265
4
        Str += *argPtr;
2266
4
        paren++;
2267
4
        break;
2268
27
      case ')':
2269
4
        Str += *argPtr;
2270
4
        paren--;
2271
4
        break;
2272
27
      case '^':
2273
2
        Str += '*';
2274
2
        if (paren == 1)
2275
2
          Str += VD->getNameAsString();
2276
2
        break;
2277
27
      default:
2278
17
        Str += *argPtr;
2279
17
        break;
2280
27
    }
2281
27
    argPtr++;
2282
27
  }
2283
2
}
2284
2285
30
void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2286
30
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2287
30
  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2288
30
  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2289
30
  if (!proto)
2290
8
    return;
2291
22
  QualType Type = proto->getReturnType();
2292
22
  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2293
22
  FdStr += " ";
2294
22
  FdStr += FD->getName();
2295
22
  FdStr +=  "(";
2296
22
  unsigned numArgs = proto->getNumParams();
2297
30
  for (unsigned i = 0; i < numArgs; 
i++8
) {
2298
8
    QualType ArgType = proto->getParamType(i);
2299
8
    RewriteBlockPointerType(FdStr, ArgType);
2300
8
    if (i+1 < numArgs)
2301
2
      FdStr += ", ";
2302
8
  }
2303
22
  FdStr +=  ");\n";
2304
22
  InsertText(FunLocStart, FdStr);
2305
22
  CurFunctionDeclToDeclareForBlock = nullptr;
2306
22
}
2307
2308
// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2309
2
void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2310
2
  if (SuperConstructorFunctionDecl)
2311
1
    return;
2312
1
  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2313
1
  SmallVector<QualType, 16> ArgTys;
2314
1
  QualType argT = Context->getObjCIdType();
2315
1
  assert(!argT.isNull() && "Can't find 'id' type");
2316
1
  ArgTys.push_back(argT);
2317
1
  ArgTys.push_back(argT);
2318
1
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2319
1
                                               ArgTys);
2320
1
  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2321
1
                                                     SourceLocation(),
2322
1
                                                     SourceLocation(),
2323
1
                                                     msgSendIdent, msgSendType,
2324
1
                                                     nullptr, SC_Extern);
2325
1
}
2326
2327
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2328
36
void RewriteObjC::SynthMsgSendFunctionDecl() {
2329
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2330
36
  SmallVector<QualType, 16> ArgTys;
2331
36
  QualType argT = Context->getObjCIdType();
2332
36
  assert(!argT.isNull() && "Can't find 'id' type");
2333
36
  ArgTys.push_back(argT);
2334
36
  argT = Context->getObjCSelType();
2335
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2336
36
  ArgTys.push_back(argT);
2337
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2338
36
                                               ArgTys, /*variadic=*/true);
2339
36
  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2340
36
                                             SourceLocation(),
2341
36
                                             SourceLocation(),
2342
36
                                             msgSendIdent, msgSendType,
2343
36
                                             nullptr, SC_Extern);
2344
36
}
2345
2346
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2347
36
void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2348
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2349
36
  SmallVector<QualType, 16> ArgTys;
2350
36
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2351
36
                                      SourceLocation(), SourceLocation(),
2352
36
                                      &Context->Idents.get("objc_super"));
2353
36
  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2354
36
  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2355
36
  ArgTys.push_back(argT);
2356
36
  argT = Context->getObjCSelType();
2357
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2358
36
  ArgTys.push_back(argT);
2359
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2360
36
                                               ArgTys, /*variadic=*/true);
2361
36
  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2362
36
                                                  SourceLocation(),
2363
36
                                                  SourceLocation(),
2364
36
                                                  msgSendIdent, msgSendType,
2365
36
                                                  nullptr, SC_Extern);
2366
36
}
2367
2368
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2369
36
void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2370
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2371
36
  SmallVector<QualType, 16> ArgTys;
2372
36
  QualType argT = Context->getObjCIdType();
2373
36
  assert(!argT.isNull() && "Can't find 'id' type");
2374
36
  ArgTys.push_back(argT);
2375
36
  argT = Context->getObjCSelType();
2376
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2377
36
  ArgTys.push_back(argT);
2378
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2379
36
                                               ArgTys, /*variadic=*/true);
2380
36
  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2381
36
                                                  SourceLocation(),
2382
36
                                                  SourceLocation(),
2383
36
                                                  msgSendIdent, msgSendType,
2384
36
                                                  nullptr, SC_Extern);
2385
36
}
2386
2387
// SynthMsgSendSuperStretFunctionDecl -
2388
// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2389
36
void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2390
36
  IdentifierInfo *msgSendIdent =
2391
36
    &Context->Idents.get("objc_msgSendSuper_stret");
2392
36
  SmallVector<QualType, 16> ArgTys;
2393
36
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2394
36
                                      SourceLocation(), SourceLocation(),
2395
36
                                      &Context->Idents.get("objc_super"));
2396
36
  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2397
36
  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2398
36
  ArgTys.push_back(argT);
2399
36
  argT = Context->getObjCSelType();
2400
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2401
36
  ArgTys.push_back(argT);
2402
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2403
36
                                               ArgTys, /*variadic=*/true);
2404
36
  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2405
36
                                                       SourceLocation(),
2406
36
                                                       SourceLocation(),
2407
36
                                                       msgSendIdent,
2408
36
                                                       msgSendType, nullptr,
2409
36
                                                       SC_Extern);
2410
36
}
2411
2412
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2413
36
void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2414
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2415
36
  SmallVector<QualType, 16> ArgTys;
2416
36
  QualType argT = Context->getObjCIdType();
2417
36
  assert(!argT.isNull() && "Can't find 'id' type");
2418
36
  ArgTys.push_back(argT);
2419
36
  argT = Context->getObjCSelType();
2420
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2421
36
  ArgTys.push_back(argT);
2422
36
  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2423
36
                                               ArgTys, /*variadic=*/true);
2424
36
  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2425
36
                                                  SourceLocation(),
2426
36
                                                  SourceLocation(),
2427
36
                                                  msgSendIdent, msgSendType,
2428
36
                                                  nullptr, SC_Extern);
2429
36
}
2430
2431
// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2432
36
void RewriteObjC::SynthGetClassFunctionDecl() {
2433
36
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2434
36
  SmallVector<QualType, 16> ArgTys;
2435
36
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2436
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2437
36
                                                ArgTys);
2438
36
  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2439
36
                                              SourceLocation(),
2440
36
                                              SourceLocation(),
2441
36
                                              getClassIdent, getClassType,
2442
36
                                              nullptr, SC_Extern);
2443
36
}
2444
2445
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2446
36
void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2447
36
  IdentifierInfo *getSuperClassIdent =
2448
36
    &Context->Idents.get("class_getSuperclass");
2449
36
  SmallVector<QualType, 16> ArgTys;
2450
36
  ArgTys.push_back(Context->getObjCClassType());
2451
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2452
36
                                                ArgTys);
2453
36
  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2454
36
                                                   SourceLocation(),
2455
36
                                                   SourceLocation(),
2456
36
                                                   getSuperClassIdent,
2457
36
                                                   getClassType, nullptr,
2458
36
                                                   SC_Extern);
2459
36
}
2460
2461
// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2462
36
void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2463
36
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2464
36
  SmallVector<QualType, 16> ArgTys;
2465
36
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2466
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2467
36
                                                ArgTys);
2468
36
  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469
36
                                                  SourceLocation(),
2470
36
                                                  SourceLocation(),
2471
36
                                                  getClassIdent, getClassType,
2472
36
                                                  nullptr, SC_Extern);
2473
36
}
2474
2475
18
Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2476
18
  assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2477
18
  QualType strType = getConstantStringStructType();
2478
18
2479
18
  std::string S = "__NSConstantStringImpl_";
2480
18
2481
18
  std::string tmpName = InFileName;
2482
18
  unsigned i;
2483
1.87k
  for (i=0; i < tmpName.length(); 
i++1.85k
) {
2484
1.85k
    char c = tmpName.at(i);
2485
1.85k
    // replace any non-alphanumeric characters with '_'.
2486
1.85k
    if (!isAlphanumeric(c))
2487
286
      tmpName[i] = '_';
2488
1.85k
  }
2489
18
  S += tmpName;
2490
18
  S += "_";
2491
18
  S += utostr(NumObjCStringLiterals++);
2492
18
2493
18
  Preamble += "static __NSConstantStringImpl " + S;
2494
18
  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2495
18
  Preamble += "0x000007c8,"; // utf8_str
2496
18
  // The pretty printer for StringLiteral handles escape characters properly.
2497
18
  std::string prettyBufS;
2498
18
  llvm::raw_string_ostream prettyBuf(prettyBufS);
2499
18
  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2500
18
  Preamble += prettyBuf.str();
2501
18
  Preamble += ",";
2502
18
  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2503
18
2504
18
  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2505
18
                                   SourceLocation(), &Context->Idents.get(S),
2506
18
                                   strType, nullptr, SC_Static);
2507
18
  DeclRefExpr *DRE = new (Context)
2508
18
      DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2509
18
  Expr *Unop = new (Context)
2510
18
      UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2511
18
                    VK_RValue, OK_Ordinary, SourceLocation(), false);
2512
18
  // cast to NSConstantString *
2513
18
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2514
18
                                            CK_CPointerToObjCPointerCast, Unop);
2515
18
  ReplaceStmt(Exp, cast);
2516
18
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2517
18
  return cast;
2518
18
}
2519
2520
// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2521
6
QualType RewriteObjC::getSuperStructType() {
2522
6
  if (!SuperStructDecl) {
2523
2
    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2524
2
                                         SourceLocation(), SourceLocation(),
2525
2
                                         &Context->Idents.get("objc_super"));
2526
2
    QualType FieldTypes[2];
2527
2
2528
2
    // struct objc_object *receiver;
2529
2
    FieldTypes[0] = Context->getObjCIdType();
2530
2
    // struct objc_class *super;
2531
2
    FieldTypes[1] = Context->getObjCClassType();
2532
2
2533
2
    // Create fields
2534
6
    for (unsigned i = 0; i < 2; 
++i4
) {
2535
4
      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2536
4
                                                 SourceLocation(),
2537
4
                                                 SourceLocation(), nullptr,
2538
4
                                                 FieldTypes[i], nullptr,
2539
4
                                                 /*BitWidth=*/nullptr,
2540
4
                                                 /*Mutable=*/false,
2541
4
                                                 ICIS_NoInit));
2542
4
    }
2543
2
2544
2
    SuperStructDecl->completeDefinition();
2545
2
  }
2546
6
  return Context->getTagDeclType(SuperStructDecl);
2547
6
}
2548
2549
18
QualType RewriteObjC::getConstantStringStructType() {
2550
18
  if (!ConstantStringDecl) {
2551
4
    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2552
4
                                            SourceLocation(), SourceLocation(),
2553
4
                         &Context->Idents.get("__NSConstantStringImpl"));
2554
4
    QualType FieldTypes[4];
2555
4
2556
4
    // struct objc_object *receiver;
2557
4
    FieldTypes[0] = Context->getObjCIdType();
2558
4
    // int flags;
2559
4
    FieldTypes[1] = Context->IntTy;
2560
4
    // char *str;
2561
4
    FieldTypes[2] = Context->getPointerType(Context->CharTy);
2562
4
    // long length;
2563
4
    FieldTypes[3] = Context->LongTy;
2564
4
2565
4
    // Create fields
2566
20
    for (unsigned i = 0; i < 4; 
++i16
) {
2567
16
      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2568
16
                                                    ConstantStringDecl,
2569
16
                                                    SourceLocation(),
2570
16
                                                    SourceLocation(), nullptr,
2571
16
                                                    FieldTypes[i], nullptr,
2572
16
                                                    /*BitWidth=*/nullptr,
2573
16
                                                    /*Mutable=*/true,
2574
16
                                                    ICIS_NoInit));
2575
16
    }
2576
4
2577
4
    ConstantStringDecl->completeDefinition();
2578
4
  }
2579
18
  return Context->getTagDeclType(ConstantStringDecl);
2580
18
}
2581
2582
CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2583
                                                QualType msgSendType,
2584
                                                QualType returnType,
2585
                                                SmallVectorImpl<QualType> &ArgTypes,
2586
                                                SmallVectorImpl<Expr*> &MsgExprs,
2587
1
                                                ObjCMethodDecl *Method) {
2588
1
  // Create a reference to the objc_msgSend_stret() declaration.
2589
1
  DeclRefExpr *STDRE =
2590
1
      new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false,
2591
1
                                msgSendType, VK_LValue, SourceLocation());
2592
1
  // Need to cast objc_msgSend_stret to "void *" (see above comment).
2593
1
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2594
1
                                  Context->getPointerType(Context->VoidTy),
2595
1
                                  CK_BitCast, STDRE);
2596
1
  // Now do the "normal" pointer to function cast.
2597
1
  QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2598
1
                                            Method ? Method->isVariadic()
2599
1
                                                   : 
false0
);
2600
1
  castType = Context->getPointerType(castType);
2601
1
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2602
1
                                            cast);
2603
1
2604
1
  // Don't forget the parens to enforce the proper binding.
2605
1
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2606
1
2607
1
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2608
1
  CallExpr *STCE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2609
1
                                    VK_RValue, SourceLocation());
2610
1
  return STCE;
2611
1
}
2612
2613
Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2614
                                    SourceLocation StartLoc,
2615
115
                                    SourceLocation EndLoc) {
2616
115
  if (!SelGetUidFunctionDecl)
2617
14
    SynthSelGetUidFunctionDecl();
2618
115
  if (!MsgSendFunctionDecl)
2619
36
    SynthMsgSendFunctionDecl();
2620
115
  if (!MsgSendSuperFunctionDecl)
2621
36
    SynthMsgSendSuperFunctionDecl();
2622
115
  if (!MsgSendStretFunctionDecl)
2623
36
    SynthMsgSendStretFunctionDecl();
2624
115
  if (!MsgSendSuperStretFunctionDecl)
2625
36
    SynthMsgSendSuperStretFunctionDecl();
2626
115
  if (!MsgSendFpretFunctionDecl)
2627
36
    SynthMsgSendFpretFunctionDecl();
2628
115
  if (!GetClassFunctionDecl)
2629
36
    SynthGetClassFunctionDecl();
2630
115
  if (!GetSuperClassFunctionDecl)
2631
36
    SynthGetSuperClassFunctionDecl();
2632
115
  if (!GetMetaClassFunctionDecl)
2633
36
    SynthGetMetaClassFunctionDecl();
2634
115
2635
115
  // default to objc_msgSend().
2636
115
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2637
115
  // May need to use objc_msgSend_stret() as well.
2638
115
  FunctionDecl *MsgSendStretFlavor = nullptr;
2639
115
  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2640
103
    QualType resultType = mDecl->getReturnType();
2641
103
    if (resultType->isRecordType())
2642
1
      MsgSendStretFlavor = MsgSendStretFunctionDecl;
2643
102
    else if (resultType->isRealFloatingType())
2644
0
      MsgSendFlavor = MsgSendFpretFunctionDecl;
2645
103
  }
2646
115
2647
115
  // Synthesize a call to objc_msgSend().
2648
115
  SmallVector<Expr*, 8> MsgExprs;
2649
115
  switch (Exp->getReceiverKind()) {
2650
115
  case ObjCMessageExpr::SuperClass: {
2651
1
    MsgSendFlavor = MsgSendSuperFunctionDecl;
2652
1
    if (MsgSendStretFlavor)
2653
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2654
1
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2655
1
2656
1
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2657
1
2658
1
    SmallVector<Expr*, 4> InitExprs;
2659
1
2660
1
    // set the receiver to self, the first argument to all methods.
2661
1
    InitExprs.push_back(
2662
1
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2663
1
                               CK_BitCast,
2664
1
                   new (Context) DeclRefExpr(*Context,
2665
1
                                             CurMethodDef->getSelfDecl(),
2666
1
                                             false,
2667
1
                                             Context->getObjCIdType(),
2668
1
                                             VK_RValue,
2669
1
                                             SourceLocation()))
2670
1
                        ); // set the 'receiver'.
2671
1
2672
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2673
1
    SmallVector<Expr*, 8> ClsExprs;
2674
1
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2675
1
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2676
1
                                                 ClsExprs, StartLoc, EndLoc);
2677
1
    // (Class)objc_getClass("CurrentClass")
2678
1
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2679
1
                                             Context->getObjCClassType(),
2680
1
                                             CK_BitCast, Cls);
2681
1
    ClsExprs.clear();
2682
1
    ClsExprs.push_back(ArgExpr);
2683
1
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2684
1
                                       StartLoc, EndLoc);
2685
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2686
1
    // To turn off a warning, type-cast to 'id'
2687
1
    InitExprs.push_back( // set 'super class', using class_getSuperclass().
2688
1
                        NoTypeInfoCStyleCastExpr(Context,
2689
1
                                                 Context->getObjCIdType(),
2690
1
                                                 CK_BitCast, Cls));
2691
1
    // struct objc_super
2692
1
    QualType superType = getSuperStructType();
2693
1
    Expr *SuperRep;
2694
1
2695
1
    if (LangOpts.MicrosoftExt) {
2696
1
      SynthSuperConstructorFunctionDecl();
2697
1
      // Simulate a constructor call...
2698
1
      DeclRefExpr *DRE = new (Context)
2699
1
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2700
1
                      VK_LValue, SourceLocation());
2701
1
      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
2702
1
                                  VK_LValue, SourceLocation());
2703
1
      // The code for super is a little tricky to prevent collision with
2704
1
      // the structure definition in the header. The rewriter has it's own
2705
1
      // internal definition (__rw_objc_super) that is uses. This is why
2706
1
      // we need the cast below. For example:
2707
1
      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2708
1
      //
2709
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2710
1
                               Context->getPointerType(SuperRep->getType()),
2711
1
                                             VK_RValue, OK_Ordinary,
2712
1
                                             SourceLocation(), false);
2713
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2714
1
                                          Context->getPointerType(superType),
2715
1
                                          CK_BitCast, SuperRep);
2716
1
    } else {
2717
0
      // (struct objc_super) { <exprs from above> }
2718
0
      InitListExpr *ILE =
2719
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2720
0
                                   SourceLocation());
2721
0
      TypeSourceInfo *superTInfo
2722
0
        = Context->getTrivialTypeSourceInfo(superType);
2723
0
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2724
0
                                                   superType, VK_LValue,
2725
0
                                                   ILE, false);
2726
0
      // struct objc_super *
2727
0
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2728
0
                               Context->getPointerType(SuperRep->getType()),
2729
0
                                             VK_RValue, OK_Ordinary,
2730
0
                                             SourceLocation(), false);
2731
0
    }
2732
1
    MsgExprs.push_back(SuperRep);
2733
1
    break;
2734
115
  }
2735
115
2736
115
  case ObjCMessageExpr::Class: {
2737
17
    SmallVector<Expr*, 8> ClsExprs;
2738
17
    ObjCInterfaceDecl *Class
2739
17
      = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2740
17
    IdentifierInfo *clsName = Class->getIdentifier();
2741
17
    ClsExprs.push_back(getStringLiteral(clsName->getName()));
2742
17
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2743
17
                                                 StartLoc, EndLoc);
2744
17
    MsgExprs.push_back(Cls);
2745
17
    break;
2746
115
  }
2747
115
2748
115
  case ObjCMessageExpr::SuperInstance:{
2749
2
    MsgSendFlavor = MsgSendSuperFunctionDecl;
2750
2
    if (MsgSendStretFlavor)
2751
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2752
2
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2753
2
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2754
2
    SmallVector<Expr*, 4> InitExprs;
2755
2
2756
2
    InitExprs.push_back(
2757
2
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2758
2
                               CK_BitCast,
2759
2
                   new (Context) DeclRefExpr(*Context,
2760
2
                                             CurMethodDef->getSelfDecl(),
2761
2
                                             false,
2762
2
                                             Context->getObjCIdType(),
2763
2
                                             VK_RValue, SourceLocation()))
2764
2
                        ); // set the 'receiver'.
2765
2
2766
2
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2767
2
    SmallVector<Expr*, 8> ClsExprs;
2768
2
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2769
2
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2770
2
                                                 StartLoc, EndLoc);
2771
2
    // (Class)objc_getClass("CurrentClass")
2772
2
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2773
2
                                                 Context->getObjCClassType(),
2774
2
                                                 CK_BitCast, Cls);
2775
2
    ClsExprs.clear();
2776
2
    ClsExprs.push_back(ArgExpr);
2777
2
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2778
2
                                       StartLoc, EndLoc);
2779
2
2780
2
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2781
2
    // To turn off a warning, type-cast to 'id'
2782
2
    InitExprs.push_back(
2783
2
      // set 'super class', using class_getSuperclass().
2784
2
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2785
2
                               CK_BitCast, Cls));
2786
2
    // struct objc_super
2787
2
    QualType superType = getSuperStructType();
2788
2
    Expr *SuperRep;
2789
2
2790
2
    if (LangOpts.MicrosoftExt) {
2791
1
      SynthSuperConstructorFunctionDecl();
2792
1
      // Simulate a constructor call...
2793
1
      DeclRefExpr *DRE = new (Context)
2794
1
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2795
1
                      VK_LValue, SourceLocation());
2796
1
      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
2797
1
                                  VK_LValue, SourceLocation());
2798
1
      // The code for super is a little tricky to prevent collision with
2799
1
      // the structure definition in the header. The rewriter has it's own
2800
1
      // internal definition (__rw_objc_super) that is uses. This is why
2801
1
      // we need the cast below. For example:
2802
1
      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2803
1
      //
2804
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2805
1
                               Context->getPointerType(SuperRep->getType()),
2806
1
                               VK_RValue, OK_Ordinary,
2807
1
                               SourceLocation(), false);
2808
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2809
1
                               Context->getPointerType(superType),
2810
1
                               CK_BitCast, SuperRep);
2811
1
    } else {
2812
1
      // (struct objc_super) { <exprs from above> }
2813
1
      InitListExpr *ILE =
2814
1
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2815
1
                                   SourceLocation());
2816
1
      TypeSourceInfo *superTInfo
2817
1
        = Context->getTrivialTypeSourceInfo(superType);
2818
1
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2819
1
                                                   superType, VK_RValue, ILE,
2820
1
                                                   false);
2821
1
    }
2822
2
    MsgExprs.push_back(SuperRep);
2823
2
    break;
2824
115
  }
2825
115
2826
115
  case ObjCMessageExpr::Instance: {
2827
95
    // Remove all type-casts because it may contain objc-style types; e.g.
2828
95
    // Foo<Proto> *.
2829
95
    Expr *recExpr = Exp->getInstanceReceiver();
2830
99
    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2831
4
      recExpr = CE->getSubExpr();
2832
95
    CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2833
95
                    ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2834
0
                                     ? CK_BlockPointerToObjCPointerCast
2835
0
                                     : CK_CPointerToObjCPointerCast;
2836
95
2837
95
    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2838
95
                                       CK, recExpr);
2839
95
    MsgExprs.push_back(recExpr);
2840
95
    break;
2841
115
  }
2842
115
  }
2843
115
2844
115
  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2845
115
  SmallVector<Expr*, 8> SelExprs;
2846
115
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2847
115
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2848
115
                                                  SelExprs, StartLoc, EndLoc);
2849
115
  MsgExprs.push_back(SelExp);
2850
115
2851
115
  // Now push any user supplied arguments.
2852
166
  for (unsigned i = 0; i < Exp->getNumArgs(); 
i++51
) {
2853
51
    Expr *userExpr = Exp->getArg(i);
2854
51
    // Make all implicit casts explicit...ICE comes in handy:-)
2855
51
    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2856
15
      // Reuse the ICE type, it is exactly what the doctor ordered.
2857
15
      QualType type = ICE->getType();
2858
15
      if (needToScanForQualifiers(type))
2859
1
        type = Context->getObjCIdType();
2860
15
      // Make sure we convert "type (^)(...)" to "type (*)(...)".
2861
15
      (void)convertBlockPointerToFunctionPointer(type);
2862
15
      const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2863
15
      CastKind CK;
2864
15
      if (SubExpr->getType()->isIntegralType(*Context) &&
2865
15
          
type->isBooleanType()6
) {
2866
1
        CK = CK_IntegralToBoolean;
2867
14
      } else if (type->isObjCObjectPointerType()) {
2868
7
        if (SubExpr->getType()->isBlockPointerType()) {
2869
0
          CK = CK_BlockPointerToObjCPointerCast;
2870
7
        } else if (SubExpr->getType()->isPointerType()) {
2871
0
          CK = CK_CPointerToObjCPointerCast;
2872
7
        } else {
2873
7
          CK = CK_BitCast;
2874
7
        }
2875
7
      } else {
2876
7
        CK = CK_BitCast;
2877
7
      }
2878
15
2879
15
      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2880
15
    }
2881
36
    // Make id<P...> cast into an 'id' cast.
2882
36
    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2883
20
      if (CE->getType()->isObjCQualifiedIdType()) {
2884
2
        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2885
1
          userExpr = CE->getSubExpr();
2886
1
        CastKind CK;
2887
1
        if (userExpr->getType()->isIntegralType(*Context)) {
2888
1
          CK = CK_IntegralToPointer;
2889
1
        } else 
if (0
userExpr->getType()->isBlockPointerType()0
) {
2890
0
          CK = CK_BlockPointerToObjCPointerCast;
2891
0
        } else if (userExpr->getType()->isPointerType()) {
2892
0
          CK = CK_CPointerToObjCPointerCast;
2893
0
        } else {
2894
0
          CK = CK_BitCast;
2895
0
        }
2896
1
        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2897
1
                                            CK, userExpr);
2898
1
      }
2899
20
    }
2900
51
    MsgExprs.push_back(userExpr);
2901
51
    // We've transferred the ownership to MsgExprs. For now, we *don't* null
2902
51
    // out the argument in the original expression (since we aren't deleting
2903
51
    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2904
51
    //Exp->setArg(i, 0);
2905
51
  }
2906
115
  // Generate the funky cast.
2907
115
  CastExpr *cast;
2908
115
  SmallVector<QualType, 8> ArgTypes;
2909
115
  QualType returnType;
2910
115
2911
115
  // Push 'id' and 'SEL', the 2 implicit arguments.
2912
115
  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2913
3
    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2914
112
  else
2915
112
    ArgTypes.push_back(Context->getObjCIdType());
2916
115
  ArgTypes.push_back(Context->getObjCSelType());
2917
115
  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2918
103
    // Push any user argument types.
2919
103
    for (const auto *PI : OMD->parameters()) {
2920
35
      QualType t = PI->getType()->isObjCQualifiedIdType()
2921
35
                     ? 
Context->getObjCIdType()1
2922
35
                     : 
PI->getType()34
;
2923
35
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
2924
35
      (void)convertBlockPointerToFunctionPointer(t);
2925
35
      ArgTypes.push_back(t);
2926
35
    }
2927
103
    returnType = Exp->getType();
2928
103
    convertToUnqualifiedObjCType(returnType);
2929
103
    (void)convertBlockPointerToFunctionPointer(returnType);
2930
103
  } else {
2931
12
    returnType = Context->getObjCIdType();
2932
12
  }
2933
115
  // Get the type, we will need to reference it in a couple spots.
2934
115
  QualType msgSendType = MsgSendFlavor->getType();
2935
115
2936
115
  // Create a reference to the objc_msgSend() declaration.
2937
115
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2938
115
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2939
115
2940
115
  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2941
115
  // If we don't do this cast, we get the following bizarre warning/note:
2942
115
  // xx.m:13: warning: function called through a non-compatible type
2943
115
  // xx.m:13: note: if this code is reached, the program will abort
2944
115
  cast = NoTypeInfoCStyleCastExpr(Context,
2945
115
                                  Context->getPointerType(Context->VoidTy),
2946
115
                                  CK_BitCast, DRE);
2947
115
2948
115
  // Now do the "normal" pointer to function cast.
2949
115
  // If we don't have a method decl, force a variadic cast.
2950
115
  const ObjCMethodDecl *MD = Exp->getMethodDecl();
2951
115
  QualType castType =
2952
115
    getSimpleFunctionType(returnType, ArgTypes, MD ? 
MD->isVariadic()103
:
true12
);
2953
115
  castType = Context->getPointerType(castType);
2954
115
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2955
115
                                  cast);
2956
115
2957
115
  // Don't forget the parens to enforce the proper binding.
2958
115
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2959
115
2960
115
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2961
115
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2962
115
                                  VK_RValue, EndLoc);
2963
115
  Stmt *ReplacingStmt = CE;
2964
115
  if (MsgSendStretFlavor) {
2965
1
    // We have the method which returns a struct/union. Must also generate
2966
1
    // call to objc_msgSend_stret and hang both varieties on a conditional
2967
1
    // expression which dictate which one to envoke depending on size of
2968
1
    // method's return type.
2969
1
2970
1
    CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2971
1
                                               msgSendType, returnType,
2972
1
                                               ArgTypes, MsgExprs,
2973
1
                                               Exp->getMethodDecl());
2974
1
2975
1
    // Build sizeof(returnType)
2976
1
    UnaryExprOrTypeTraitExpr *sizeofExpr =
2977
1
       new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2978
1
                                 Context->getTrivialTypeSourceInfo(returnType),
2979
1
                                 Context->getSizeType(), SourceLocation(),
2980
1
                                 SourceLocation());
2981
1
    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2982
1
    // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2983
1
    // For X86 it is more complicated and some kind of target specific routine
2984
1
    // is needed to decide what to do.
2985
1
    unsigned IntSize =
2986
1
      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2987
1
    IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2988
1
                                                   llvm::APInt(IntSize, 8),
2989
1
                                                   Context->IntTy,
2990
1
                                                   SourceLocation());
2991
1
    BinaryOperator *lessThanExpr =
2992
1
      new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2993
1
                                   VK_RValue, OK_Ordinary, SourceLocation(),
2994
1
                                   FPOptions());
2995
1
    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2996
1
    ConditionalOperator *CondExpr =
2997
1
      new (Context) ConditionalOperator(lessThanExpr,
2998
1
                                        SourceLocation(), CE,
2999
1
                                        SourceLocation(), STCE,
3000
1
                                        returnType, VK_RValue, OK_Ordinary);
3001
1
    ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3002
1
                                            CondExpr);
3003
1
  }
3004
115
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3005
115
  return ReplacingStmt;
3006
115
}
3007
3008
79
Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3009
79
  Stmt *ReplacingStmt =
3010
79
      SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3011
79
3012
79
  // Now do the actual rewrite.
3013
79
  ReplaceStmt(Exp, ReplacingStmt);
3014
79
3015
79
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3016
79
  return ReplacingStmt;
3017
79
}
3018
3019
// typedef struct objc_object Protocol;
3020
0
QualType RewriteObjC::getProtocolType() {
3021
0
  if (!ProtocolTypeDecl) {
3022
0
    TypeSourceInfo *TInfo
3023
0
      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3024
0
    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3025
0
                                           SourceLocation(), SourceLocation(),
3026
0
                                           &Context->Idents.get("Protocol"),
3027
0
                                           TInfo);
3028
0
  }
3029
0
  return Context->getTypeDeclType(ProtocolTypeDecl);
3030
0
}
3031
3032
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3033
/// a synthesized/forward data reference (to the protocol's metadata).
3034
/// The forward references (and metadata) are generated in
3035
/// RewriteObjC::HandleTranslationUnit().
3036
0
Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3037
0
  std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3038
0
  IdentifierInfo *ID = &Context->Idents.get(Name);
3039
0
  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3040
0
                                SourceLocation(), ID, getProtocolType(),
3041
0
                                nullptr, SC_Extern);
3042
0
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3043
0
      *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3044
0
  Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3045
0
                             Context->getPointerType(DRE->getType()),
3046
0
                             VK_RValue, OK_Ordinary, SourceLocation(), false);
3047
0
  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3048
0
                                                CK_BitCast,
3049
0
                                                DerefExpr);
3050
0
  ReplaceStmt(Exp, castExpr);
3051
0
  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3052
0
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3053
0
  return castExpr;
3054
0
}
3055
3056
bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3057
39
                                             const char *endBuf) {
3058
878
  while (startBuf < endBuf) {
3059
839
    if (*startBuf == '#') {
3060
0
      // Skip whitespace.
3061
0
      for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3062
0
        ;
3063
0
      if (!strncmp(startBuf, "if", strlen("if")) ||
3064
0
          !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3065
0
          !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3066
0
          !strncmp(startBuf, "define", strlen("define")) ||
3067
0
          !strncmp(startBuf, "undef", strlen("undef")) ||
3068
0
          !strncmp(startBuf, "else", strlen("else")) ||
3069
0
          !strncmp(startBuf, "elif", strlen("elif")) ||
3070
0
          !strncmp(startBuf, "endif", strlen("endif")) ||
3071
0
          !strncmp(startBuf, "pragma", strlen("pragma")) ||
3072
0
          !strncmp(startBuf, "include", strlen("include")) ||
3073
0
          !strncmp(startBuf, "import", strlen("import")) ||
3074
0
          !strncmp(startBuf, "include_next", strlen("include_next")))
3075
0
        return true;
3076
839
    }
3077
839
    startBuf++;
3078
839
  }
3079
39
  return false;
3080
39
}
3081
3082
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3083
/// an objective-c class with ivars.
3084
void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3085
120
                                               std::string &Result) {
3086
120
  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3087
120
  assert(CDecl->getName() != "" &&
3088
120
         "Name missing in SynthesizeObjCInternalStruct");
3089
120
  // Do not synthesize more than once.
3090
120
  if (ObjCSynthesizedStructs.count(CDecl))
3091
0
    return;
3092
120
  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3093
120
  int NumIvars = CDecl->ivar_size();
3094
120
  SourceLocation LocStart = CDecl->getBeginLoc();
3095
120
  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3096
120
3097
120
  const char *startBuf = SM->getCharacterData(LocStart);
3098
120
  const char *endBuf = SM->getCharacterData(LocEnd);
3099
120
3100
120
  // If no ivars and no root or if its root, directly or indirectly,
3101
120
  // have no ivars (thus not synthesized) then no need to synthesize this class.
3102
120
  if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3103
120
      
(81
!RCDecl81
||
!ObjCSynthesizedStructs.count(RCDecl)10
)) {
3104
80
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3105
80
    ReplaceText(LocStart, endBuf-startBuf, Result);
3106
80
    return;
3107
80
  }
3108
40
3109
40
  // FIXME: This has potential of causing problem. If
3110
40
  // SynthesizeObjCInternalStruct is ever called recursively.
3111
40
  Result += "\nstruct ";
3112
40
  Result += CDecl->getNameAsString();
3113
40
  if (LangOpts.MicrosoftExt)
3114
30
    Result += "_IMPL";
3115
40
3116
40
  if (NumIvars > 0) {
3117
39
    const char *cursor = strchr(startBuf, '{');
3118
39
    assert((cursor && endBuf)
3119
39
           && "SynthesizeObjCInternalStruct - malformed @interface");
3120
39
    // If the buffer contains preprocessor directives, we do more fine-grained
3121
39
    // rewrites. This is intended to fix code that looks like (which occurs in
3122
39
    // NSURL.h, for example):
3123
39
    //
3124
39
    // #ifdef XYZ
3125
39
    // @interface Foo : NSObject
3126
39
    // #else
3127
39
    // @interface FooBar : NSObject
3128
39
    // #endif
3129
39
    // {
3130
39
    //    int i;
3131
39
    // }
3132
39
    // @end
3133
39
    //
3134
39
    // This clause is segregated to avoid breaking the common case.
3135
39
    if (BufferContainsPPDirectives(startBuf, cursor)) {
3136
0
      SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3137
0
                                  CDecl->getAtStartLoc();
3138
0
      const char *endHeader = SM->getCharacterData(L);
3139
0
      endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3140
0
3141
0
      if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3142
0
        // advance to the end of the referenced protocols.
3143
0
        while (endHeader < cursor && *endHeader != '>') endHeader++;
3144
0
        endHeader++;
3145
0
      }
3146
0
      // rewrite the original header
3147
0
      ReplaceText(LocStart, endHeader-startBuf, Result);
3148
39
    } else {
3149
39
      // rewrite the original header *without* disturbing the '{'
3150
39
      ReplaceText(LocStart, cursor-startBuf, Result);
3151
39
    }
3152
39
    if (RCDecl && 
ObjCSynthesizedStructs.count(RCDecl)6
) {
3153
1
      Result = "\n    struct ";
3154
1
      Result += RCDecl->getNameAsString();
3155
1
      Result += "_IMPL ";
3156
1
      Result += RCDecl->getNameAsString();
3157
1
      Result += "_IVARS;\n";
3158
1
3159
1
      // insert the super class structure definition.
3160
1
      SourceLocation OnePastCurly =
3161
1
        LocStart.getLocWithOffset(cursor-startBuf+1);
3162
1
      InsertText(OnePastCurly, Result);
3163
1
    }
3164
39
    cursor++; // past '{'
3165
39
3166
39
    // Now comment out any visibility specifiers.
3167
1.11k
    while (cursor < endBuf) {
3168
1.07k
      if (*cursor == '@') {
3169
12
        SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3170
12
        // Skip whitespace.
3171
12
        for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; 
++cursor0
)
3172
0
          /*scan*/;
3173
12
3174
12
        // FIXME: presence of @public, etc. inside comment results in
3175
12
        // this transformation as well, which is still correct c-code.
3176
12
        if (!strncmp(cursor, "public", strlen("public")) ||
3177
12
            
!strncmp(cursor, "private", strlen("private"))4
||
3178
12
            
!strncmp(cursor, "package", strlen("package"))0
||
3179
12
            
!strncmp(cursor, "protected", strlen("protected"))0
)
3180
12
          InsertText(atLoc, "// ");
3181
12
      }
3182
1.06k
      // FIXME: If there are cases where '<' is used in ivar declaration part
3183
1.06k
      // of user code, then scan the ivar list and use needToScanForQualifiers
3184
1.06k
      // for type checking.
3185
1.06k
      else if (*cursor == '<') {
3186
4
        SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3187
4
        InsertText(atLoc, "/* ");
3188
4
        cursor = strchr(cursor, '>');
3189
4
        cursor++;
3190
4
        atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3191
4
        InsertText(atLoc, " */");
3192
1.06k
      } else if (*cursor == '^') { // rewrite block specifier.
3193
1
        SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3194
1
        ReplaceText(caretLoc, 1, "*");
3195
1
      }
3196
1.07k
      cursor++;
3197
1.07k
    }
3198
39
    // Don't forget to add a ';'!!
3199
39
    InsertText(LocEnd.getLocWithOffset(1), ";");
3200
39
  } else { // we don't have any instance variables - insert super struct.
3201
1
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3202
1
    Result += " {\n    struct ";
3203
1
    Result += RCDecl->getNameAsString();
3204
1
    Result += "_IMPL ";
3205
1
    Result += RCDecl->getNameAsString();
3206
1
    Result += "_IVARS;\n};\n";
3207
1
    ReplaceText(LocStart, endBuf-startBuf, Result);
3208
1
  }
3209
40
  // Mark this struct as having been generated.
3210
40
  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3211
40
    
llvm_unreachable0
("struct already synthesize- SynthesizeObjCInternalStruct");
3212
40
}
3213
3214
//===----------------------------------------------------------------------===//
3215
// Meta Data Emission
3216
//===----------------------------------------------------------------------===//
3217
3218
/// RewriteImplementations - This routine rewrites all method implementations
3219
/// and emits meta-data.
3220
3221
53
void RewriteObjC::RewriteImplementations() {
3222
53
  int ClsDefCount = ClassImplementation.size();
3223
53
  int CatDefCount = CategoryImplementation.size();
3224
53
3225
53
  // Rewrite implemented methods
3226
117
  for (int i = 0; i < ClsDefCount; 
i++64
)
3227
64
    RewriteImplementationDecl(ClassImplementation[i]);
3228
53
3229
59
  for (int i = 0; i < CatDefCount; 
i++6
)
3230
6
    RewriteImplementationDecl(CategoryImplementation[i]);
3231
53
}
3232
3233
void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3234
                                     const std::string &Name,
3235
208
                                     ValueDecl *VD, bool def) {
3236
208
  assert(BlockByRefDeclNo.count(VD) &&
3237
208
         "RewriteByRefString: ByRef decl missing");
3238
208
  if (def)
3239
61
    ResultStr += "struct ";
3240
208
  ResultStr += "__Block_byref_" + Name +
3241
208
    "_" + utostr(BlockByRefDeclNo[VD]) ;
3242
208
}
3243
3244
825
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3245
825
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3246
430
    return (Var->isFunctionOrMethodVarDecl() && 
!Var->hasLocalStorage()233
);
3247
395
  return false;
3248
395
}
3249
3250
std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3251
                                                   StringRef funcName,
3252
68
                                                   std::string Tag) {
3253
68
  const FunctionType *AFT = CE->getFunctionType();
3254
68
  QualType RT = AFT->getReturnType();
3255
68
  std::string StructRef = "struct " + Tag;
3256
68
  std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3257
68
                  funcName.str() + "_" + "block_func_" + utostr(i);
3258
68
3259
68
  BlockDecl *BD = CE->getBlockDecl();
3260
68
3261
68
  if (isa<FunctionNoProtoType>(AFT)) {
3262
0
    // No user-supplied arguments. Still need to pass in a pointer to the
3263
0
    // block (to reference imported block decl refs).
3264
0
    S += "(" + StructRef + " *__cself)";
3265
68
  } else if (BD->param_empty()) {
3266
58
    S += "(" + StructRef + " *__cself)";
3267
58
  } else {
3268
10
    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3269
10
    assert(FT && "SynthesizeBlockFunc: No function proto");
3270
10
    S += '(';
3271
10
    // first add the implicit argument.
3272
10
    S += StructRef + " *__cself, ";
3273
10
    std::string ParamStr;
3274
10
    for (BlockDecl::param_iterator AI = BD->param_begin(),
3275
23
         E = BD->param_end(); AI != E; 
++AI13
) {
3276
13
      if (AI != BD->param_begin()) 
S += ", "3
;
3277
13
      ParamStr = (*AI)->getNameAsString();
3278
13
      QualType QT = (*AI)->getType();
3279
13
      (void)convertBlockPointerToFunctionPointer(QT);
3280
13
      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3281
13
      S += ParamStr;
3282
13
    }
3283
10
    if (FT->isVariadic()) {
3284
0
      if (!BD->param_empty()) S += ", ";
3285
0
      S += "...";
3286
0
    }
3287
10
    S += ')';
3288
10
  }
3289
68
  S += " {\n";
3290
68
3291
68
  // Create local declarations to avoid rewriting all closure decl ref exprs.
3292
68
  // First, emit a declaration for all "by ref" decls.
3293
68
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3294
104
       E = BlockByRefDecls.end(); I != E; 
++I36
) {
3295
36
    S += "  ";
3296
36
    std::string Name = (*I)->getNameAsString();
3297
36
    std::string TypeString;
3298
36
    RewriteByRefString(TypeString, Name, (*I));
3299
36
    TypeString += " *";
3300
36
    Name = TypeString + Name;
3301
36
    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3302
36
  }
3303
68
  // Next, emit a declaration for all "by copy" declarations.
3304
68
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3305
110
       E = BlockByCopyDecls.end(); I != E; 
++I42
) {
3306
42
    S += "  ";
3307
42
    // Handle nested closure invocation. For example:
3308
42
    //
3309
42
    //   void (^myImportedClosure)(void);
3310
42
    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
3311
42
    //
3312
42
    //   void (^anotherClosure)(void);
3313
42
    //   anotherClosure = ^(void) {
3314
42
    //     myImportedClosure(); // import and invoke the closure
3315
42
    //   };
3316
42
    //
3317
42
    if (isTopLevelBlockPointerType((*I)->getType())) {
3318
2
      RewriteBlockPointerTypeVariable(S, (*I));
3319
2
      S += " = (";
3320
2
      RewriteBlockPointerType(S, (*I)->getType());
3321
2
      S += ")";
3322
2
      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3323
2
    }
3324
40
    else {
3325
40
      std::string Name = (*I)->getNameAsString();
3326
40
      QualType QT = (*I)->getType();
3327
40
      if (HasLocalVariableExternalStorage(*I))
3328
2
        QT = Context->getPointerType(QT);
3329
40
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3330
40
      S += Name + " = __cself->" +
3331
40
                              (*I)->getNameAsString() + "; // bound by copy\n";
3332
40
    }
3333
42
  }
3334
68
  std::string RewrittenStr = RewrittenBlockExprs[CE];
3335
68
  const char *cstr = RewrittenStr.c_str();
3336
341
  while (*cstr++ != '{') 
;273
3337
68
  S += cstr;
3338
68
  S += "\n";
3339
68
  return S;
3340
68
}
3341
3342
std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3343
                                                   StringRef funcName,
3344
41
                                                   std::string Tag) {
3345
41
  std::string StructRef = "struct " + Tag;
3346
41
  std::string S = "static void __";
3347
41
3348
41
  S += funcName;
3349
41
  S += "_block_copy_" + utostr(i);
3350
41
  S += "(" + StructRef;
3351
41
  S += "*dst, " + StructRef;
3352
41
  S += "*src) {";
3353
69
  for (ValueDecl *VD : ImportedBlockDecls) {
3354
69
    S += "_Block_object_assign((void*)&dst->";
3355
69
    S += VD->getNameAsString();
3356
69
    S += ", (void*)src->";
3357
69
    S += VD->getNameAsString();
3358
69
    if (BlockByRefDeclsPtrSet.count(VD))
3359
36
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3360
33
    else if (VD->getType()->isBlockPointerType())
3361
3
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3362
30
    else
3363
30
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3364
69
  }
3365
41
  S += "}\n";
3366
41
3367
41
  S += "\nstatic void __";
3368
41
  S += funcName;
3369
41
  S += "_block_dispose_" + utostr(i);
3370
41
  S += "(" + StructRef;
3371
41
  S += "*src) {";
3372
69
  for (ValueDecl *VD : ImportedBlockDecls) {
3373
69
    S += "_Block_object_dispose((void*)src->";
3374
69
    S += VD->getNameAsString();
3375
69
    if (BlockByRefDeclsPtrSet.count(VD))
3376
36
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3377
33
    else if (VD->getType()->isBlockPointerType())
3378
3
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3379
30
    else
3380
30
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3381
69
  }
3382
41
  S += "}\n";
3383
41
  return S;
3384
41
}
3385
3386
std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3387
68
                                             std::string Desc) {
3388
68
  std::string S = "\nstruct " + Tag;
3389
68
  std::string Constructor = "  " + Tag;
3390
68
3391
68
  S += " {\n  struct __block_impl impl;\n";
3392
68
  S += "  struct " + Desc;
3393
68
  S += "* Desc;\n";
3394
68
3395
68
  Constructor += "(void *fp, "; // Invoke function pointer.
3396
68
  Constructor += "struct " + Desc; // Descriptor pointer.
3397
68
  Constructor += " *desc";
3398
68
3399
68
  if (BlockDeclRefs.size()) {
3400
47
    // Output all "by copy" declarations.
3401
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3402
89
         E = BlockByCopyDecls.end(); I != E; 
++I42
) {
3403
42
      S += "  ";
3404
42
      std::string FieldName = (*I)->getNameAsString();
3405
42
      std::string ArgName = "_" + FieldName;
3406
42
      // Handle nested closure invocation. For example:
3407
42
      //
3408
42
      //   void (^myImportedBlock)(void);
3409
42
      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
3410
42
      //
3411
42
      //   void (^anotherBlock)(void);
3412
42
      //   anotherBlock = ^(void) {
3413
42
      //     myImportedBlock(); // import and invoke the closure
3414
42
      //   };
3415
42
      //
3416
42
      if (isTopLevelBlockPointerType((*I)->getType())) {
3417
2
        S += "struct __block_impl *";
3418
2
        Constructor += ", void *" + ArgName;
3419
40
      } else {
3420
40
        QualType QT = (*I)->getType();
3421
40
        if (HasLocalVariableExternalStorage(*I))
3422
2
          QT = Context->getPointerType(QT);
3423
40
        QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3424
40
        QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3425
40
        Constructor += ", " + ArgName;
3426
40
      }
3427
42
      S += FieldName + ";\n";
3428
42
    }
3429
47
    // Output all "by ref" declarations.
3430
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3431
83
         E = BlockByRefDecls.end(); I != E; 
++I36
) {
3432
36
      S += "  ";
3433
36
      std::string FieldName = (*I)->getNameAsString();
3434
36
      std::string ArgName = "_" + FieldName;
3435
36
      {
3436
36
        std::string TypeString;
3437
36
        RewriteByRefString(TypeString, FieldName, (*I));
3438
36
        TypeString += " *";
3439
36
        FieldName = TypeString + FieldName;
3440
36
        ArgName = TypeString + ArgName;
3441
36
        Constructor += ", " + ArgName;
3442
36
      }
3443
36
      S += FieldName + "; // by ref\n";
3444
36
    }
3445
47
    // Finish writing the constructor.
3446
47
    Constructor += ", int flags=0)";
3447
47
    // Initialize all "by copy" arguments.
3448
47
    bool firsTime = true;
3449
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3450
89
         E = BlockByCopyDecls.end(); I != E; 
++I42
) {
3451
42
      std::string Name = (*I)->getNameAsString();
3452
42
        if (firsTime) {
3453
29
          Constructor += " : ";
3454
29
          firsTime = false;
3455
29
        }
3456
13
        else
3457
13
          Constructor += ", ";
3458
42
        if (isTopLevelBlockPointerType((*I)->getType()))
3459
2
          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3460
40
        else
3461
40
          Constructor += Name + "(_" + Name + ")";
3462
42
    }
3463
47
    // Initialize all "by ref" arguments.
3464
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3465
83
         E = BlockByRefDecls.end(); I != E; 
++I36
) {
3466
36
      std::string Name = (*I)->getNameAsString();
3467
36
      if (firsTime) {
3468
18
        Constructor += " : ";
3469
18
        firsTime = false;
3470
18
      }
3471
18
      else
3472
18
        Constructor += ", ";
3473
36
      Constructor += Name + "(_" + Name + "->__forwarding)";
3474
36
    }
3475
47
3476
47
    Constructor += " {\n";
3477
47
    if (GlobalVarDecl)
3478
0
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3479
47
    else
3480
47
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3481
47
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3482
47
3483
47
    Constructor += "    Desc = desc;\n";
3484
47
  } else {
3485
21
    // Finish writing the constructor.
3486
21
    Constructor += ", int flags=0) {\n";
3487
21
    if (GlobalVarDecl)
3488
4
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3489
17
    else
3490
17
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3491
21
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3492
21
    Constructor += "    Desc = desc;\n";
3493
21
  }
3494
68
  Constructor += "  ";
3495
68
  Constructor += "}\n";
3496
68
  S += Constructor;
3497
68
  S += "};\n";
3498
68
  return S;
3499
68
}
3500
3501
std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3502
                                                   std::string ImplTag, int i,
3503
                                                   StringRef FunName,
3504
68
                                                   unsigned hasCopy) {
3505
68
  std::string S = "\nstatic struct " + DescTag;
3506
68
3507
68
  S += " {\n  unsigned long reserved;\n";
3508
68
  S += "  unsigned long Block_size;\n";
3509
68
  if (hasCopy) {
3510
41
    S += "  void (*copy)(struct ";
3511
41
    S += ImplTag; S += "*, struct ";
3512
41
    S += ImplTag; S += "*);\n";
3513
41
3514
41
    S += "  void (*dispose)(struct ";
3515
41
    S += ImplTag; S += "*);\n";
3516
41
  }
3517
68
  S += "} ";
3518
68
3519
68
  S += DescTag + "_DATA = { 0, sizeof(struct ";
3520
68
  S += ImplTag + ")";
3521
68
  if (hasCopy) {
3522
41
    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3523
41
    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3524
41
  }
3525
68
  S += "};\n";
3526
68
  return S;
3527
68
}
3528
3529
void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3530
150
                                          StringRef FunName) {
3531
150
  // Insert declaration for the function in which block literal is used.
3532
150
  if (CurFunctionDeclToDeclareForBlock && 
!Blocks.empty()54
)
3533
15
    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3534
150
  bool RewriteSC = (GlobalVarDecl &&
3535
150
                    
!Blocks.empty()9
&&
3536
150
                    
GlobalVarDecl->getStorageClass() == SC_Static4
&&
3537
150
                    
GlobalVarDecl->getType().getCVRQualifiers()3
);
3538
150
  if (RewriteSC) {
3539
3
    std::string SC(" void __");
3540
3
    SC += GlobalVarDecl->getNameAsString();
3541
3
    SC += "() {}";
3542
3
    InsertText(FunLocStart, SC);
3543
3
  }
3544
150
3545
150
  // Insert closures that were part of the function.
3546
218
  for (unsigned i = 0, count=0; i < Blocks.size(); 
i++68
) {
3547
68
    CollectBlockDeclRefInfo(Blocks[i]);
3548
68
    // Need to copy-in the inner copied-in variables not actually used in this
3549
68
    // block.
3550
89
    for (int j = 0; j < InnerDeclRefsCount[i]; 
j++21
) {
3551
21
      DeclRefExpr *Exp = InnerDeclRefs[count++];
3552
21
      ValueDecl *VD = Exp->getDecl();
3553
21
      BlockDeclRefs.push_back(Exp);
3554
21
      if (!VD->hasAttr<BlocksAttr>() && 
!BlockByCopyDeclsPtrSet.count(VD)12
) {
3555
12
        BlockByCopyDeclsPtrSet.insert(VD);
3556
12
        BlockByCopyDecls.push_back(VD);
3557
12
      }
3558
21
      if (VD->hasAttr<BlocksAttr>() && 
!BlockByRefDeclsPtrSet.count(VD)9
) {
3559
9
        BlockByRefDeclsPtrSet.insert(VD);
3560
9
        BlockByRefDecls.push_back(VD);
3561
9
      }
3562
21
      // imported objects in the inner blocks not used in the outer
3563
21
      // blocks must be copied/disposed in the outer block as well.
3564
21
      if (VD->hasAttr<BlocksAttr>() ||
3565
21
          
VD->getType()->isObjCObjectPointerType()12
||
3566
21
          
VD->getType()->isBlockPointerType()1
)
3567
20
        ImportedBlockDecls.insert(VD);
3568
21
    }
3569
68
3570
68
    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3571
68
    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3572
68
3573
68
    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3574
68
3575
68
    InsertText(FunLocStart, CI);
3576
68
3577
68
    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3578
68
3579
68
    InsertText(FunLocStart, CF);
3580
68
3581
68
    if (ImportedBlockDecls.size()) {
3582
41
      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3583
41
      InsertText(FunLocStart, HF);
3584
41
    }
3585
68
    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3586
68
                                               ImportedBlockDecls.size() > 0);
3587
68
    InsertText(FunLocStart, BD);
3588
68
3589
68
    BlockDeclRefs.clear();
3590
68
    BlockByRefDecls.clear();
3591
68
    BlockByRefDeclsPtrSet.clear();
3592
68
    BlockByCopyDecls.clear();
3593
68
    BlockByCopyDeclsPtrSet.clear();
3594
68
    ImportedBlockDecls.clear();
3595
68
  }
3596
150
  if (RewriteSC) {
3597
3
    // Must insert any 'const/volatile/static here. Since it has been
3598
3
    // removed as result of rewriting of block literals.
3599
3
    std::string SC;
3600
3
    if (GlobalVarDecl->getStorageClass() == SC_Static)
3601
3
      SC = "static ";
3602
3
    if (GlobalVarDecl->getType().isConstQualified())
3603
3
      SC += "const ";
3604
3
    if (GlobalVarDecl->getType().isVolatileQualified())
3605
0
      SC += "volatile ";
3606
3
    if (GlobalVarDecl->getType().isRestrictQualified())
3607
0
      SC += "restrict ";
3608
3
    InsertText(FunLocStart, SC);
3609
3
  }
3610
150
3611
150
  Blocks.clear();
3612
150
  InnerDeclRefsCount.clear();
3613
150
  InnerDeclRefs.clear();
3614
150
  RewrittenBlockExprs.clear();
3615
150
}
3616
3617
64
void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3618
64
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3619
64
  StringRef FuncName = FD->getName();
3620
64
3621
64
  SynthesizeBlockLiterals(FunLocStart, FuncName);
3622
64
}
3623
3624
static void BuildUniqueMethodName(std::string &Name,
3625
99
                                  ObjCMethodDecl *MD) {
3626
99
  ObjCInterfaceDecl *IFace = MD->getClassInterface();
3627
99
  Name = IFace->getName();
3628
99
  Name += "__" + MD->getSelector().getAsString();
3629
99
  // Convert colons to underscores.
3630
99
  std::string::size_type loc = 0;
3631
142
  while ((loc = Name.find(':', loc)) != std::string::npos)
3632
43
    Name.replace(loc, 1, "_");
3633
99
}
3634
3635
77
void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3636
77
  // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3637
77
  // SourceLocation FunLocStart = MD->getBeginLoc();
3638
77
  SourceLocation FunLocStart = MD->getBeginLoc();
3639
77
  std::string FuncName;
3640
77
  BuildUniqueMethodName(FuncName, MD);
3641
77
  SynthesizeBlockLiterals(FunLocStart, FuncName);
3642
77
}
3643
3644
1.85k
void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3645
1.85k
  for (Stmt *SubStmt : S->children())
3646
1.71k
    if (SubStmt) {
3647
1.71k
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3648
0
        GetBlockDeclRefExprs(CBE->getBody());
3649
1.71k
      else
3650
1.71k
        GetBlockDeclRefExprs(SubStmt);
3651
1.71k
    }
3652
1.85k
  // Handle specific things.
3653
1.85k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3654
426
    if (DRE->refersToEnclosingVariableOrCapture() ||
3655
426
        
HasLocalVariableExternalStorage(DRE->getDecl())304
)
3656
140
      // FIXME: Handle enums.
3657
140
      BlockDeclRefs.push_back(DRE);
3658
1.85k
}
3659
3660
void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3661
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3662
642
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3663
642
  for (Stmt *SubStmt : S->children())
3664
574
    if (SubStmt) {
3665
574
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3666
15
        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3667
15
        GetInnerBlockDeclRefExprs(CBE->getBody(),
3668
15
                                  InnerBlockDeclRefs,
3669
15
                                  InnerContexts);
3670
15
      }
3671
559
      else
3672
559
        GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3673
574
    }
3674
642
  // Handle specific things.
3675
642
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3676
141
    if (DRE->refersToEnclosingVariableOrCapture() ||
3677
141
        
HasLocalVariableExternalStorage(DRE->getDecl())59
) {
3678
91
      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3679
90
        InnerBlockDeclRefs.push_back(DRE);
3680
91
      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3681
91
        if (Var->isFunctionOrMethodVarDecl())
3682
72
          ImportedLocalExternalDecls.insert(Var);
3683
91
    }
3684
141
  }
3685
642
}
3686
3687
/// convertFunctionTypeOfBlocks - This routine converts a function type
3688
/// whose result type may be a block pointer or whose argument type(s)
3689
/// might be block pointers to an equivalent function type replacing
3690
/// all block pointers to function pointers.
3691
68
QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3692
68
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3693
68
  // FTP will be null for closures that don't take arguments.
3694
68
  // Generate a funky cast.
3695
68
  SmallVector<QualType, 8> ArgTypes;
3696
68
  QualType Res = FT->getReturnType();
3697
68
  bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3698
68
3699
68
  if (FTP) {
3700
68
    for (auto &I : FTP->param_types()) {
3701
13
      QualType t = I;
3702
13
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3703
13
      if (convertBlockPointerToFunctionPointer(t))
3704
1
        HasBlockType = true;
3705
13
      ArgTypes.push_back(t);
3706
13
    }
3707
68
  }
3708
68
  QualType FuncType;
3709
68
  // FIXME. Does this work if block takes no argument but has a return type
3710
68
  // which is of block type?
3711
68
  if (HasBlockType)
3712
1
    FuncType = getSimpleFunctionType(Res, ArgTypes);
3713
67
  else FuncType = QualType(FT, 0);
3714
68
  return FuncType;
3715
68
}
3716
3717
14
Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3718
14
  // Navigate to relevant type information.
3719
14
  const BlockPointerType *CPT = nullptr;
3720
14
3721
14
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3722
0
    CPT = DRE->getType()->getAs<BlockPointerType>();
3723
14
  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3724
0
    CPT = MExpr->getType()->getAs<BlockPointerType>();
3725
0
  }
3726
14
  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3727
0
    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3728
0
  }
3729
14
  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3730
14
    CPT = IEXPR->getType()->getAs<BlockPointerType>();
3731
0
  else if (const ConditionalOperator *CEXPR =
3732
0
            dyn_cast<ConditionalOperator>(BlockExp)) {
3733
0
    Expr *LHSExp = CEXPR->getLHS();
3734
0
    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3735
0
    Expr *RHSExp = CEXPR->getRHS();
3736
0
    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3737
0
    Expr *CONDExp = CEXPR->getCond();
3738
0
    ConditionalOperator *CondExpr =
3739
0
      new (Context) ConditionalOperator(CONDExp,
3740
0
                                      SourceLocation(), cast<Expr>(LHSStmt),
3741
0
                                      SourceLocation(), cast<Expr>(RHSStmt),
3742
0
                                      Exp->getType(), VK_RValue, OK_Ordinary);
3743
0
    return CondExpr;
3744
0
  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3745
0
    CPT = IRE->getType()->getAs<BlockPointerType>();
3746
0
  } else if (const PseudoObjectExpr *POE
3747
0
               = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3748
0
    CPT = POE->getType()->castAs<BlockPointerType>();
3749
0
  } else {
3750
0
    assert(false && "RewriteBlockClass: Bad type");
3751
0
  }
3752
14
  assert(CPT && "RewriteBlockClass: Bad type");
3753
14
  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3754
14
  assert(FT && "RewriteBlockClass: Bad type");
3755
14
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3756
14
  // FTP will be null for closures that don't take arguments.
3757
14
3758
14
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3759
14
                                      SourceLocation(), SourceLocation(),
3760
14
                                      &Context->Idents.get("__block_impl"));
3761
14
  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3762
14
3763
14
  // Generate a funky cast.
3764
14
  SmallVector<QualType, 8> ArgTypes;
3765
14
3766
14
  // Push the block argument type.
3767
14
  ArgTypes.push_back(PtrBlock);
3768
14
  if (FTP) {
3769
14
    for (auto &I : FTP->param_types()) {
3770
6
      QualType t = I;
3771
6
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3772
6
      if (!convertBlockPointerToFunctionPointer(t))
3773
6
        convertToUnqualifiedObjCType(t);
3774
6
      ArgTypes.push_back(t);
3775
6
    }
3776
14
  }
3777
14
  // Now do the pointer to function cast.
3778
14
  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3779
14
3780
14
  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3781
14
3782
14
  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3783
14
                                               CK_BitCast,
3784
14
                                               const_cast<Expr*>(BlockExp));
3785
14
  // Don't forget the parens to enforce the proper binding.
3786
14
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3787
14
                                          BlkCast);
3788
14
  //PE->dump();
3789
14
3790
14
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3791
14
                                    SourceLocation(),
3792
14
                                    &Context->Idents.get("FuncPtr"),
3793
14
                                    Context->VoidPtrTy, nullptr,
3794
14
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
3795
14
                                    ICIS_NoInit);
3796
14
  MemberExpr *ME = MemberExpr::CreateImplicit(
3797
14
      *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
3798
14
3799
14
  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3800
14
                                                CK_BitCast, ME);
3801
14
  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3802
14
3803
14
  SmallVector<Expr*, 8> BlkExprs;
3804
14
  // Add the implicit argument.
3805
14
  BlkExprs.push_back(BlkCast);
3806
14
  // Add the user arguments.
3807
14
  for (CallExpr::arg_iterator I = Exp->arg_begin(),
3808
20
       E = Exp->arg_end(); I != E; 
++I6
) {
3809
6
    BlkExprs.push_back(*I);
3810
6
  }
3811
14
  CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
3812
14
                                  VK_RValue, SourceLocation());
3813
14
  return CE;
3814
14
}
3815
3816
// We need to return the rewritten expression to handle cases where the
3817
// BlockDeclRefExpr is embedded in another expression being rewritten.
3818
// For example:
3819
//
3820
// int main() {
3821
//    __block Foo *f;
3822
//    __block int i;
3823
//
3824
//    void (^myblock)() = ^() {
3825
//        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3826
//        i = 77;
3827
//    };
3828
//}
3829
35
Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3830
35
  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3831
35
  // for each DeclRefExp where BYREFVAR is name of the variable.
3832
35
  ValueDecl *VD = DeclRefExp->getDecl();
3833
35
  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3834
35
                 
HasLocalVariableExternalStorage(DeclRefExp->getDecl())8
;
3835
35
3836
35
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3837
35
                                    SourceLocation(),
3838
35
                                    &Context->Idents.get("__forwarding"),
3839
35
                                    Context->VoidPtrTy, nullptr,
3840
35
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
3841
35
                                    ICIS_NoInit);
3842
35
  MemberExpr *ME =
3843
35
      MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
3844
35
                                 FD->getType(), VK_LValue, OK_Ordinary);
3845
35
3846
35
  StringRef Name = VD->getName();
3847
35
  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3848
35
                         &Context->Idents.get(Name),
3849
35
                         Context->VoidPtrTy, nullptr,
3850
35
                         /*BitWidth=*/nullptr, /*Mutable=*/true,
3851
35
                         ICIS_NoInit);
3852
35
  ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
3853
35
                                  VK_LValue, OK_Ordinary);
3854
35
3855
35
  // Need parens to enforce precedence.
3856
35
  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3857
35
                                          DeclRefExp->getExprLoc(),
3858
35
                                          ME);
3859
35
  ReplaceStmt(DeclRefExp, PE);
3860
35
  return PE;
3861
35
}
3862
3863
// Rewrites the imported local variable V with external storage
3864
// (static, extern, etc.) as *V
3865
//
3866
15
Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3867
15
  ValueDecl *VD = DRE->getDecl();
3868
15
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3869
15
    if (!ImportedLocalExternalDecls.count(Var))
3870
6
      return DRE;
3871
9
  Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3872
9
                                          VK_LValue, OK_Ordinary,
3873
9
                                          DRE->getLocation(), false);
3874
9
  // Need parens to enforce precedence.
3875
9
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3876
9
                                          Exp);
3877
9
  ReplaceStmt(DRE, PE);
3878
9
  return PE;
3879
9
}
3880
3881
31
void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3882
31
  SourceLocation LocStart = CE->getLParenLoc();
3883
31
  SourceLocation LocEnd = CE->getRParenLoc();
3884
31
3885
31
  // Need to avoid trying to rewrite synthesized casts.
3886
31
  if (LocStart.isInvalid())
3887
0
    return;
3888
31
  // Need to avoid trying to rewrite casts contained in macros.
3889
31
  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3890
0
    return;
3891
31
3892
31
  const char *startBuf = SM->getCharacterData(LocStart);
3893
31
  const char *endBuf = SM->getCharacterData(LocEnd);
3894
31
  QualType QT = CE->getType();
3895
31
  const Type* TypePtr = QT->getAs<Type>();
3896
31
  if (isa<TypeOfExprType>(TypePtr)) {
3897
3
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3898
3
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3899
3
    std::string TypeAsString = "(";
3900
3
    RewriteBlockPointerType(TypeAsString, QT);
3901
3
    TypeAsString += ")";
3902
3
    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3903
3
    return;
3904
3
  }
3905
28
  // advance the location to startArgList.
3906
28
  const char *argPtr = startBuf;
3907
28
3908
249
  while (*argPtr++ && (argPtr < endBuf)) {
3909
221
    switch (*argPtr) {
3910
221
    case '^':
3911
0
      // Replace the '^' with '*'.
3912
0
      LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3913
0
      ReplaceText(LocStart, 1, "*");
3914
0
      break;
3915
221
    }
3916
221
  }
3917
28
}
3918
3919
20
void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3920
20
  SourceLocation DeclLoc = FD->getLocation();
3921
20
  unsigned parenCount = 0;
3922
20
3923
20
  // We have 1 or more arguments that have closure pointers.
3924
20
  const char *startBuf = SM->getCharacterData(DeclLoc);
3925
20
  const char *startArgList = strchr(startBuf, '(');
3926
20
3927
20
  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3928
20
3929
20
  parenCount++;
3930
20
  // advance the location to startArgList.
3931
20
  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3932
20
  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3933
20
3934
20
  const char *argPtr = startArgList;
3935
20
3936
390
  while (*argPtr++ && parenCount) {
3937
370
    switch (*argPtr) {
3938
370
    case '^':
3939
20
      // Replace the '^' with '*'.
3940
20
      DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3941
20
      ReplaceText(DeclLoc, 1, "*");
3942
20
      break;
3943
370
    case '(':
3944
40
      parenCount++;
3945
40
      break;
3946
370
    case ')':
3947
60
      parenCount--;
3948
60
      break;
3949
370
    }
3950
370
  }
3951
20
}
3952
3953
46
bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3954
46
  const FunctionProtoType *FTP;
3955
46
  const PointerType *PT = QT->getAs<PointerType>();
3956
46
  if (PT) {
3957
1
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3958
45
  } else {
3959
45
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3960
45
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3961
45
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3962
45
  }
3963
46
  if (FTP) {
3964
44
    for (const auto &I : FTP->param_types())
3965
30
      if (isTopLevelBlockPointerType(I))
3966
3
        return true;
3967
44
  }
3968
46
  
return false43
;
3969
46
}
3970
3971
42
bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3972
42
  const FunctionProtoType *FTP;
3973
42
  const PointerType *PT = QT->getAs<PointerType>();
3974
42
  if (PT) {
3975
0
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3976
42
  } else {
3977
42
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3978
42
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3979
42
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3980
42
  }
3981
42
  if (FTP) {
3982
40
    for (const auto &I : FTP->param_types()) {
3983
16
      if (I->isObjCQualifiedIdType())
3984
5
        return true;
3985
11
      if (I->isObjCObjectPointerType() &&
3986
11
          
I->getPointeeType()->isObjCQualifiedInterfaceType()4
)
3987
1
        return true;
3988
11
    }
3989
40
3990
40
  }
3991
42
  
return false36
;
3992
42
}
3993
3994
void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3995
9
                                     const char *&RParen) {
3996
9
  const char *argPtr = strchr(Name, '(');
3997
9
  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3998
9
3999
9
  LParen = argPtr; // output the start.
4000
9
  argPtr++; // skip past the left paren.
4001
9
  unsigned parenCount = 1;
4002
9
4003
884
  while (*argPtr && parenCount) {
4004
875
    switch (*argPtr) {
4005
875
    
case '(': parenCount++; break10
;
4006
875
    
case ')': parenCount--; break19
;
4007
875
    
default: break846
;
4008
875
    }
4009
875
    if (parenCount) 
argPtr++866
;
4010
875
  }
4011
9
  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4012
9
  RParen = argPtr; // output the end
4013
9
}
4014
4015
65
void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4016
65
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4017
20
    RewriteBlockPointerFunctionArgs(FD);
4018
20
    return;
4019
20
  }
4020
45
  // Handle Variables and Typedefs.
4021
45
  SourceLocation DeclLoc = ND->getLocation();
4022
45
  QualType DeclT;
4023
45
  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4024
25
    DeclT = VD->getType();
4025
20
  else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4026
20
    DeclT = TDD->getUnderlyingType();
4027
0
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4028
0
    DeclT = FD->getType();
4029
0
  else
4030
0
    llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4031
45
4032
45
  const char *startBuf = SM->getCharacterData(DeclLoc);
4033
45
  const char *endBuf = startBuf;
4034
45
  // scan backward (from the decl location) for the end of the previous decl.
4035
92
  while (*startBuf != '^' && 
*startBuf != ';'47
&&
startBuf != MainFileStart47
)
4036
47
    startBuf--;
4037
45
  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4038
45
  std::string buf;
4039
45
  unsigned OrigLength=0;
4040
45
  // *startBuf != '^' if we are dealing with a pointer to function that
4041
45
  // may take block argument types (which will be handled below).
4042
45
  if (*startBuf == '^') {
4043
45
    // Replace the '^' with '*', computing a negative offset.
4044
45
    buf = '*';
4045
45
    startBuf++;
4046
45
    OrigLength++;
4047
45
  }
4048
440
  while (*startBuf != ')') {
4049
395
    buf += *startBuf;
4050
395
    startBuf++;
4051
395
    OrigLength++;
4052
395
  }
4053
45
  buf += ')';
4054
45
  OrigLength++;
4055
45
4056
45
  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4057
45
      
PointerTypeTakesAnyObjCQualifiedType(DeclT)42
) {
4058
9
    // Replace the '^' with '*' for arguments.
4059
9
    // Replace id<P> with id/*<>*/
4060
9
    DeclLoc = ND->getLocation();
4061
9
    startBuf = SM->getCharacterData(DeclLoc);
4062
9
    const char *argListBegin, *argListEnd;
4063
9
    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4064
453
    while (argListBegin < argListEnd) {
4065
444
      if (*argListBegin == '^')
4066
5
        buf += '*';
4067
439
      else if (*argListBegin ==  '<') {
4068
17
        buf += "/*";
4069
17
        buf += *argListBegin++;
4070
17
        OrigLength++;
4071
431
        while (*argListBegin != '>') {
4072
414
          buf += *argListBegin++;
4073
414
          OrigLength++;
4074
414
        }
4075
17
        buf += *argListBegin;
4076
17
        buf += "*/";
4077
17
      }
4078
422
      else
4079
422
        buf += *argListBegin;
4080
444
      argListBegin++;
4081
444
      OrigLength++;
4082
444
    }
4083
9
    buf += ')';
4084
9
    OrigLength++;
4085
9
  }
4086
45
  ReplaceText(Start, OrigLength, buf);
4087
45
}
4088
4089
/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4090
/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4091
///                    struct Block_byref_id_object *src) {
4092
///  _Block_object_assign (&_dest->object, _src->object,
4093
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4094
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4095
///  _Block_object_assign(&_dest->object, _src->object,
4096
///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4097
///                       [|BLOCK_FIELD_IS_WEAK]) // block
4098
/// }
4099
/// And:
4100
/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4101
///  _Block_object_dispose(_src->object,
4102
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4103
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4104
///  _Block_object_dispose(_src->object,
4105
///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4106
///                         [|BLOCK_FIELD_IS_WEAK]) // block
4107
/// }
4108
4109
std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4110
8
                                                          int flag) {
4111
8
  std::string S;
4112
8
  if (CopyDestroyCache.count(flag))
4113
3
    return S;
4114
5
  CopyDestroyCache.insert(flag);
4115
5
  S = "static void __Block_byref_id_object_copy_";
4116
5
  S += utostr(flag);
4117
5
  S += "(void *dst, void *src) {\n";
4118
5
4119
5
  // offset into the object pointer is computed as:
4120
5
  // void * + void* + int + int + void* + void *
4121
5
  unsigned IntSize =
4122
5
  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4123
5
  unsigned VoidPtrSize =
4124
5
  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4125
5
4126
5
  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4127
5
  S += " _Block_object_assign((char*)dst + ";
4128
5
  S += utostr(offset);
4129
5
  S += ", *(void * *) ((char*)src + ";
4130
5
  S += utostr(offset);
4131
5
  S += "), ";
4132
5
  S += utostr(flag);
4133
5
  S += ");\n}\n";
4134
5
4135
5
  S += "static void __Block_byref_id_object_dispose_";
4136
5
  S += utostr(flag);
4137
5
  S += "(void *src) {\n";
4138
5
  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4139
5
  S += utostr(offset);
4140
5
  S += "), ";
4141
5
  S += utostr(flag);
4142
5
  S += ");\n}\n";
4143
5
  return S;
4144
5
}
4145
4146
/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4147
/// the declaration into:
4148
/// struct __Block_byref_ND {
4149
/// void *__isa;                  // NULL for everything except __weak pointers
4150
/// struct __Block_byref_ND *__forwarding;
4151
/// int32_t __flags;
4152
/// int32_t __size;
4153
/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4154
/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4155
/// typex ND;
4156
/// };
4157
///
4158
/// It then replaces declaration of ND variable with:
4159
/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4160
///                               __size=sizeof(struct __Block_byref_ND),
4161
///                               ND=initializer-if-any};
4162
///
4163
///
4164
25
void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4165
25
  // Insert declaration for the function in which block literal is
4166
25
  // used.
4167
25
  if (CurFunctionDeclToDeclareForBlock)
4168
15
    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4169
25
  int flag = 0;
4170
25
  int isa = 0;
4171
25
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4172
25
  if (DeclLoc.isInvalid())
4173
0
    // If type location is missing, it is because of missing type (a warning).
4174
0
    // Use variable's location which is good for this case.
4175
0
    DeclLoc = ND->getLocation();
4176
25
  const char *startBuf = SM->getCharacterData(DeclLoc);
4177
25
  SourceLocation X = ND->getEndLoc();
4178
25
  X = SM->getExpansionLoc(X);
4179
25
  const char *endBuf = SM->getCharacterData(X);
4180
25
  std::string Name(ND->getNameAsString());
4181
25
  std::string ByrefType;
4182
25
  RewriteByRefString(ByrefType, Name, ND, true);
4183
25
  ByrefType += " {\n";
4184
25
  ByrefType += "  void *__isa;\n";
4185
25
  RewriteByRefString(ByrefType, Name, ND);
4186
25
  ByrefType += " *__forwarding;\n";
4187
25
  ByrefType += " int __flags;\n";
4188
25
  ByrefType += " int __size;\n";
4189
25
  // Add void *__Block_byref_id_object_copy;
4190
25
  // void *__Block_byref_id_object_dispose; if needed.
4191
25
  QualType Ty = ND->getType();
4192
25
  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4193
25
  if (HasCopyAndDispose) {
4194
8
    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4195
8
    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4196
8
  }
4197
25
4198
25
  QualType T = Ty;
4199
25
  (void)convertBlockPointerToFunctionPointer(T);
4200
25
  T.getAsStringInternal(Name, Context->getPrintingPolicy());
4201
25
4202
25
  ByrefType += " " + Name + ";\n";
4203
25
  ByrefType += "};\n";
4204
25
  // Insert this type in global scope. It is needed by helper function.
4205
25
  SourceLocation FunLocStart;
4206
25
  if (CurFunctionDef)
4207
17
     FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4208
8
  else {
4209
8
    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4210
8
    FunLocStart = CurMethodDef->getBeginLoc();
4211
8
  }
4212
25
  InsertText(FunLocStart, ByrefType);
4213
25
  if (Ty.isObjCGCWeak()) {
4214
2
    flag |= BLOCK_FIELD_IS_WEAK;
4215
2
    isa = 1;
4216
2
  }
4217
25
4218
25
  if (HasCopyAndDispose) {
4219
8
    flag = BLOCK_BYREF_CALLER;
4220
8
    QualType Ty = ND->getType();
4221
8
    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4222
8
    if (Ty->isBlockPointerType())
4223
2
      flag |= BLOCK_FIELD_IS_BLOCK;
4224
6
    else
4225
6
      flag |= BLOCK_FIELD_IS_OBJECT;
4226
8
    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4227
8
    if (!HF.empty())
4228
5
      InsertText(FunLocStart, HF);
4229
8
  }
4230
25
4231
25
  // struct __Block_byref_ND ND =
4232
25
  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4233
25
  //  initializer-if-any};
4234
25
  bool hasInit = (ND->getInit() != nullptr);
4235
25
  unsigned flags = 0;
4236
25
  if (HasCopyAndDispose)
4237
8
    flags |= BLOCK_HAS_COPY_DISPOSE;
4238
25
  Name = ND->getNameAsString();
4239
25
  ByrefType.clear();
4240
25
  RewriteByRefString(ByrefType, Name, ND);
4241
25
  std::string ForwardingCastType("(");
4242
25
  ForwardingCastType += ByrefType + " *)";
4243
25
  if (!hasInit) {
4244
5
    ByrefType += " " + Name + " = {(void*)";
4245
5
    ByrefType += utostr(isa);
4246
5
    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4247
5
    ByrefType += utostr(flags);
4248
5
    ByrefType += ", ";
4249
5
    ByrefType += "sizeof(";
4250
5
    RewriteByRefString(ByrefType, Name, ND);
4251
5
    ByrefType += ")";
4252
5
    if (HasCopyAndDispose) {
4253
2
      ByrefType += ", __Block_byref_id_object_copy_";
4254
2
      ByrefType += utostr(flag);
4255
2
      ByrefType += ", __Block_byref_id_object_dispose_";
4256
2
      ByrefType += utostr(flag);
4257
2
    }
4258
5
    ByrefType += "};\n";
4259
5
    unsigned nameSize = Name.size();
4260
5
    // for block or function pointer declaration. Name is already
4261
5
    // part of the declaration.
4262
5
    if (Ty->isBlockPointerType() || 
Ty->isFunctionPointerType()3
)
4263
2
      nameSize = 1;
4264
5
    ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4265
5
  }
4266
20
  else {
4267
20
    SourceLocation startLoc;
4268
20
    Expr *E = ND->getInit();
4269
20
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4270
1
      startLoc = ECE->getLParenLoc();
4271
19
    else
4272
19
      startLoc = E->getBeginLoc();
4273
20
    startLoc = SM->getExpansionLoc(startLoc);
4274
20
    endBuf = SM->getCharacterData(startLoc);
4275
20
    ByrefType += " " + Name;
4276
20
    ByrefType += " = {(void*)";
4277
20
    ByrefType += utostr(isa);
4278
20
    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4279
20
    ByrefType += utostr(flags);
4280
20
    ByrefType += ", ";
4281
20
    ByrefType += "sizeof(";
4282
20
    RewriteByRefString(ByrefType, Name, ND);
4283
20
    ByrefType += "), ";
4284
20
    if (HasCopyAndDispose) {
4285
6
      ByrefType += "__Block_byref_id_object_copy_";
4286
6
      ByrefType += utostr(flag);
4287
6
      ByrefType += ", __Block_byref_id_object_dispose_";
4288
6
      ByrefType += utostr(flag);
4289
6
      ByrefType += ", ";
4290
6
    }
4291
20
    ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4292
20
4293
20
    // Complete the newly synthesized compound expression by inserting a right
4294
20
    // curly brace before the end of the declaration.
4295
20
    // FIXME: This approach avoids rewriting the initializer expression. It
4296
20
    // also assumes there is only one declarator. For example, the following
4297
20
    // isn't currently supported by this routine (in general):
4298
20
    //
4299
20
    // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4300
20
    //
4301
20
    const char *startInitializerBuf = SM->getCharacterData(startLoc);
4302
20
    const char *semiBuf = strchr(startInitializerBuf, ';');
4303
20
    assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4304
20
    SourceLocation semiLoc =
4305
20
      startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4306
20
4307
20
    InsertText(semiLoc, "}");
4308
20
  }
4309
25
}
4310
4311
136
void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4312
136
  // Add initializers for any closure decl refs.
4313
136
  GetBlockDeclRefExprs(Exp->getBody());
4314
136
  if (BlockDeclRefs.size()) {
4315
80
    // Unique all "by copy" declarations.
4316
220
    for (unsigned i = 0; i < BlockDeclRefs.size(); 
i++140
)
4317
140
      if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4318
84
        if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4319
60
          BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4320
60
          BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4321
60
        }
4322
84
      }
4323
80
    // Unique all "by ref" declarations.
4324
220
    for (unsigned i = 0; i < BlockDeclRefs.size(); 
i++140
)
4325
140
      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4326
56
        if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4327
54
          BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4328
54
          BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4329
54
        }
4330
56
      }
4331
80
    // Find any imported blocks...they will need special attention.
4332
220
    for (unsigned i = 0; i < BlockDeclRefs.size(); 
i++140
)
4333
140
      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4334
140
          
BlockDeclRefs[i]->getType()->isObjCObjectPointerType()84
||
4335
140
          
BlockDeclRefs[i]->getType()->isBlockPointerType()38
)
4336
110
        ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4337
80
  }
4338
136
}
4339
4340
214
FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4341
214
  IdentifierInfo *ID = &Context->Idents.get(name);
4342
214
  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4343
214
  return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4344
214
                              SourceLocation(), ID, FType, nullptr, SC_Extern,
4345
214
                              false, false);
4346
214
}
4347
4348
Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4349
68
                     const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4350
68
  const BlockDecl *block = Exp->getBlockDecl();
4351
68
  Blocks.push_back(Exp);
4352
68
4353
68
  CollectBlockDeclRefInfo(Exp);
4354
68
4355
68
  // Add inner imported variables now used in current block.
4356
68
 int countOfInnerDecls = 0;
4357
68
  if (!InnerBlockDeclRefs.empty()) {
4358
136
    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); 
i++90
) {
4359
90
      DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4360
90
      ValueDecl *VD = Exp->getDecl();
4361
90
      if (!VD->hasAttr<BlocksAttr>() && 
!BlockByCopyDeclsPtrSet.count(VD)54
) {
4362
12
      // We need to save the copied-in variables in nested
4363
12
      // blocks because it is needed at the end for some of the API generations.
4364
12
      // See SynthesizeBlockLiterals routine.
4365
12
        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4366
12
        BlockDeclRefs.push_back(Exp);
4367
12
        BlockByCopyDeclsPtrSet.insert(VD);
4368
12
        BlockByCopyDecls.push_back(VD);
4369
12
      }
4370
90
      if (VD->hasAttr<BlocksAttr>() && 
!BlockByRefDeclsPtrSet.count(VD)36
) {
4371
9
        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4372
9
        BlockDeclRefs.push_back(Exp);
4373
9
        BlockByRefDeclsPtrSet.insert(VD);
4374
9
        BlockByRefDecls.push_back(VD);
4375
9
      }
4376
90
    }
4377
46
    // Find any imported blocks...they will need special attention.
4378
136
    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); 
i++90
)
4379
90
      if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4380
90
          
InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType()54
||
4381
90
          
InnerBlockDeclRefs[i]->getType()->isBlockPointerType()19
)
4382
74
        ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4383
46
  }
4384
68
  InnerDeclRefsCount.push_back(countOfInnerDecls);
4385
68
4386
68
  std::string FuncName;
4387
68
4388
68
  if (CurFunctionDef)
4389
42
    FuncName = CurFunctionDef->getNameAsString();
4390
26
  else if (CurMethodDef)
4391
22
    BuildUniqueMethodName(FuncName, CurMethodDef);
4392
4
  else if (GlobalVarDecl)
4393
4
    FuncName = std::string(GlobalVarDecl->getNameAsString());
4394
68
4395
68
  std::string BlockNumber = utostr(Blocks.size()-1);
4396
68
4397
68
  std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4398
68
  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4399
68
4400
68
  // Get a pointer to the function type so we can cast appropriately.
4401
68
  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4402
68
  QualType FType = Context->getPointerType(BFT);
4403
68
4404
68
  FunctionDecl *FD;
4405
68
  Expr *NewRep;
4406
68
4407
68
  // Simulate a constructor call...
4408
68
  FD = SynthBlockInitFunctionDecl(Tag);
4409
68
  DeclRefExpr *DRE = new (Context)
4410
68
      DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
4411
68
4412
68
  SmallVector<Expr*, 4> InitExprs;
4413
68
4414
68
  // Initialize the block function.
4415
68
  FD = SynthBlockInitFunctionDecl(Func);
4416
68
  DeclRefExpr *Arg = new (Context) DeclRefExpr(
4417
68
      *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
4418
68
  CastExpr *castExpr =
4419
68
      NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
4420
68
  InitExprs.push_back(castExpr);
4421
68
4422
68
  // Initialize the block descriptor.
4423
68
  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4424
68
4425
68
  VarDecl *NewVD = VarDecl::Create(
4426
68
      *Context, TUDecl, SourceLocation(), SourceLocation(),
4427
68
      &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4428
68
  UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4429
68
      new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
4430
68
                                VK_LValue, SourceLocation()),
4431
68
      UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
4432
68
      OK_Ordinary, SourceLocation(), false);
4433
68
  InitExprs.push_back(DescRefExpr);
4434
68
4435
68
  // Add initializers for any closure decl refs.
4436
68
  if (BlockDeclRefs.size()) {
4437
47
    Expr *Exp;
4438
47
    // Output all "by copy" declarations.
4439
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4440
89
         E = BlockByCopyDecls.end(); I != E; 
++I42
) {
4441
42
      if (isObjCType((*I)->getType())) {
4442
7
        // FIXME: Conform to ABI ([[obj retain] autorelease]).
4443
7
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4444
7
        Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4445
7
                                        VK_LValue, SourceLocation());
4446
7
        if (HasLocalVariableExternalStorage(*I)) {
4447
1
          QualType QT = (*I)->getType();
4448
1
          QT = Context->getPointerType(QT);
4449
1
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4450
1
                                            OK_Ordinary, SourceLocation(),
4451
1
                                            false);
4452
1
        }
4453
35
      } else if (isTopLevelBlockPointerType((*I)->getType())) {
4454
2
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4455
2
        Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4456
2
                                        VK_LValue, SourceLocation());
4457
2
        Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
4458
2
                                       Arg);
4459
33
      } else {
4460
33
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4461
33
        Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4462
33
                                        VK_LValue, SourceLocation());
4463
33
        if (HasLocalVariableExternalStorage(*I)) {
4464
1
          QualType QT = (*I)->getType();
4465
1
          QT = Context->getPointerType(QT);
4466
1
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4467
1
                                            OK_Ordinary, SourceLocation(),
4468
1
                                            false);
4469
1
        }
4470
33
      }
4471
42
      InitExprs.push_back(Exp);
4472
42
    }
4473
47
    // Output all "by ref" declarations.
4474
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4475
83
         E = BlockByRefDecls.end(); I != E; 
++I36
) {
4476
36
      ValueDecl *ND = (*I);
4477
36
      std::string Name(ND->getNameAsString());
4478
36
      std::string RecName;
4479
36
      RewriteByRefString(RecName, Name, ND, true);
4480
36
      IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4481
36
                                                + sizeof("struct"));
4482
36
      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4483
36
                                          SourceLocation(), SourceLocation(),
4484
36
                                          II);
4485
36
      assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4486
36
      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4487
36
4488
36
      FD = SynthBlockInitFunctionDecl((*I)->getName());
4489
36
      Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4490
36
                                      VK_LValue, SourceLocation());
4491
36
      bool isNestedCapturedVar = false;
4492
36
      if (block)
4493
77
        
for (const auto &CI : block->captures())36
{
4494
77
          const VarDecl *variable = CI.getVariable();
4495
77
          if (variable == ND && 
CI.isNested()35
) {
4496
9
            assert (CI.isByRef() &&
4497
9
                    "SynthBlockInitExpr - captured block variable is not byref");
4498
9
            isNestedCapturedVar = true;
4499
9
            break;
4500
9
          }
4501
77
        }
4502
36
      // captured nested byref variable has its address passed. Do not take
4503
36
      // its address again.
4504
36
      if (!isNestedCapturedVar)
4505
27
        Exp = new (Context) UnaryOperator(
4506
27
            Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_RValue,
4507
27
            OK_Ordinary, SourceLocation(), false);
4508
36
      Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4509
36
      InitExprs.push_back(Exp);
4510
36
    }
4511
47
  }
4512
68
  if (ImportedBlockDecls.size()) {
4513
41
    // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4514
41
    int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4515
41
    unsigned IntSize =
4516
41
      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4517
41
    Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4518
41
                                           Context->IntTy, SourceLocation());
4519
41
    InitExprs.push_back(FlagExp);
4520
41
  }
4521
68
  NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
4522
68
                            SourceLocation());
4523
68
  NewRep = new (Context) UnaryOperator(
4524
68
      NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue,
4525
68
      OK_Ordinary, SourceLocation(), false);
4526
68
  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4527
68
                                    NewRep);
4528
68
  BlockDeclRefs.clear();
4529
68
  BlockByRefDecls.clear();
4530
68
  BlockByRefDeclsPtrSet.clear();
4531
68
  BlockByCopyDecls.clear();
4532
68
  BlockByCopyDeclsPtrSet.clear();
4533
68
  ImportedBlockDecls.clear();
4534
68
  return NewRep;
4535
68
}
4536
4537
13
bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4538
13
  if (const ObjCForCollectionStmt * CS =
4539
11
      dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4540
11
        return CS->getElement() == DS;
4541
2
  return false;
4542
2
}
4543
4544
//===----------------------------------------------------------------------===//
4545
// Function Body / Expression rewriting
4546
//===----------------------------------------------------------------------===//
4547
4548
2.13k
Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4549
2.13k
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4550
2.13k
      
isa<DoStmt>(S)2.12k
||
isa<ForStmt>(S)2.12k
)
4551
7
    Stmts.push_back(S);
4552
2.12k
  else if (isa<ObjCForCollectionStmt>(S)) {
4553
18
    Stmts.push_back(S);
4554
18
    ObjCBcLabelNo.push_back(++BcLabelCount);
4555
18
  }
4556
2.13k
4557
2.13k
  // Pseudo-object operations and ivar references need special
4558
2.13k
  // treatment because we're going to recursively rewrite them.
4559
2.13k
  if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4560
36
    if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4561
14
      return RewritePropertyOrImplicitSetter(PseudoOp);
4562
22
    } else {
4563
22
      return RewritePropertyOrImplicitGetter(PseudoOp);
4564
22
    }
4565
2.09k
  } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4566
43
    return RewriteObjCIvarRefExpr(IvarRefExpr);
4567
43
  }
4568
2.05k
4569
2.05k
  SourceRange OrigStmtRange = S->getSourceRange();
4570
2.05k
4571
2.05k
  // Perform a bottom up rewrite of all children.
4572
2.05k
  for (Stmt *&childStmt : S->children())
4573
1.82k
    if (childStmt) {
4574
1.82k
      Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4575
1.82k
      if (newStmt) {
4576
1.78k
        childStmt = newStmt;
4577
1.78k
      }
4578
1.82k
    }
4579
2.05k
4580
2.05k
  if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4581
68
    SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4582
68
    llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4583
68
    InnerContexts.insert(BE->getBlockDecl());
4584
68
    ImportedLocalExternalDecls.clear();
4585
68
    GetInnerBlockDeclRefExprs(BE->getBody(),
4586
68
                              InnerBlockDeclRefs, InnerContexts);
4587
68
    // Rewrite the block body in place.
4588
68
    Stmt *SaveCurrentBody = CurrentBody;
4589
68
    CurrentBody = BE->getBody();
4590
68
    PropParentMap = nullptr;
4591
68
    // block literal on rhs of a property-dot-sytax assignment
4592
68
    // must be replaced by its synthesize ast so getRewrittenText
4593
68
    // works as expected. In this case, what actually ends up on RHS
4594
68
    // is the blockTranscribed which is the helper function for the
4595
68
    // block literal; as in: self.c = ^() {[ace ARR];};
4596
68
    bool saveDisableReplaceStmt = DisableReplaceStmt;
4597
68
    DisableReplaceStmt = false;
4598
68
    RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4599
68
    DisableReplaceStmt = saveDisableReplaceStmt;
4600
68
    CurrentBody = SaveCurrentBody;
4601
68
    PropParentMap = nullptr;
4602
68
    ImportedLocalExternalDecls.clear();
4603
68
    // Now we snarf the rewritten text and stash it away for later use.
4604
68
    std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4605
68
    RewrittenBlockExprs[BE] = Str;
4606
68
4607
68
    Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4608
68
4609
68
    //blockTranscribed->dump();
4610
68
    ReplaceStmt(S, blockTranscribed);
4611
68
    return blockTranscribed;
4612
68
  }
4613
1.98k
  // Handle specific things.
4614
1.98k
  if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4615
3
    return RewriteAtEncode(AtEncode);
4616
1.98k
4617
1.98k
  if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4618
1
    return RewriteAtSelector(AtSelector);
4619
1.98k
4620
1.98k
  if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4621
18
    return RewriteObjCStringLiteral(AtString);
4622
1.96k
4623
1.96k
  if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4624
#if 0
4625
    // Before we rewrite it, put the original message expression in a comment.
4626
    SourceLocation startLoc = MessExpr->getBeginLoc();
4627
    SourceLocation endLoc = MessExpr->getEndLoc();
4628
4629
    const char *startBuf = SM->getCharacterData(startLoc);
4630
    const char *endBuf = SM->getCharacterData(endLoc);
4631
4632
    std::string messString;
4633
    messString += "// ";
4634
    messString.append(startBuf, endBuf-startBuf+1);
4635
    messString += "\n";
4636
4637
    // FIXME: Missing definition of
4638
    // InsertText(clang::SourceLocation, char const*, unsigned int).
4639
    // InsertText(startLoc, messString);
4640
    // Tried this, but it didn't work either...
4641
    // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4642
#endif
4643
    return RewriteMessageExpr(MessExpr);
4644
79
  }
4645
1.88k
4646
1.88k
  if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4647
8
    return RewriteObjCTryStmt(StmtTry);
4648
1.87k
4649
1.87k
  if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4650
3
    return RewriteObjCSynchronizedStmt(StmtTry);
4651
1.87k
4652
1.87k
  if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4653
2
    return RewriteObjCThrowStmt(StmtThrow);
4654
1.87k
4655
1.87k
  if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4656
0
    return RewriteObjCProtocolExpr(ProtocolExp);
4657
1.87k
4658
1.87k
  if (ObjCForCollectionStmt *StmtForCollection =
4659
18
        dyn_cast<ObjCForCollectionStmt>(S))
4660
18
    return RewriteObjCForCollectionStmt(StmtForCollection,
4661
18
                                        OrigStmtRange.getEnd());
4662
1.85k
  if (BreakStmt *StmtBreakStmt =
4663
6
      dyn_cast<BreakStmt>(S))
4664
6
    return RewriteBreakStmt(StmtBreakStmt);
4665
1.84k
  if (ContinueStmt *StmtContinueStmt =
4666
2
      dyn_cast<ContinueStmt>(S))
4667
2
    return RewriteContinueStmt(StmtContinueStmt);
4668
1.84k
4669
1.84k
  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4670
1.84k
  // and cast exprs.
4671
1.84k
  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4672
141
    // FIXME: What we're doing here is modifying the type-specifier that
4673
141
    // precedes the first Decl.  In the future the DeclGroup should have
4674
141
    // a separate type-specifier that we can rewrite.
4675
141
    // NOTE: We need to avoid rewriting the DeclStmt if it is within
4676
141
    // the context of an ObjCForCollectionStmt. For example:
4677
141
    //   NSArray *someArray;
4678
141
    //   for (id <FooProtocol> index in someArray) ;
4679
141
    // This is because RewriteObjCForCollectionStmt() does textual rewriting
4680
141
    // and it depends on the original text locations/positions.
4681
141
    if (Stmts.empty() || 
!IsDeclStmtInForeachHeader(DS)13
)
4682
132
      RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4683
141
4684
141
    // Blocks rewrite rules.
4685
144
    for (auto *SD : DS->decls()) {
4686
144
      if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4687
144
        if (isTopLevelBlockPointerType(ND->getType()))
4688
21
          RewriteBlockPointerDecl(ND);
4689
123
        else if (ND->getType()->isFunctionPointerType())
4690
1
          CheckFunctionPointerDecl(ND->getType(), ND);
4691
144
        if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4692
144
          if (VD->hasAttr<BlocksAttr>()) {
4693
25
            static unsigned uniqueByrefDeclCount = 0;
4694
25
            assert(!BlockByRefDeclNo.count(ND) &&
4695
25
              "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4696
25
            BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4697
25
            RewriteByRefVar(VD);
4698
25
          }
4699
119
          else
4700
119
            RewriteTypeOfDecl(VD);
4701
144
        }
4702
144
      }
4703
144
      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4704
0
        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4705
0
          RewriteBlockPointerDecl(TD);
4706
0
        else if (TD->getUnderlyingType()->isFunctionPointerType())
4707
0
          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4708
0
      }
4709
144
    }
4710
141
  }
4711
1.84k
4712
1.84k
  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4713
31
    RewriteObjCQualifiedInterfaceTypes(CE);
4714
1.84k
4715
1.84k
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4716
1.84k
      
isa<DoStmt>(S)1.83k
||
isa<ForStmt>(S)1.83k
) {
4717
7
    assert(!Stmts.empty() && "Statement stack is empty");
4718
7
    assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4719
7
             isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4720
7
            && "Statement stack mismatch");
4721
7
    Stmts.pop_back();
4722
7
  }
4723
1.84k
  // Handle blocks rewriting.
4724
1.84k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4725
369
    ValueDecl *VD = DRE->getDecl();
4726
369
    if (VD->hasAttr<BlocksAttr>())
4727
35
      return RewriteBlockDeclRefExpr(DRE);
4728
334
    if (HasLocalVariableExternalStorage(VD))
4729
15
      return RewriteLocalVariableExternalStorage(DRE);
4730
1.79k
  }
4731
1.79k
4732
1.79k
  if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4733
119
    if (CE->getCallee()->getType()->isBlockPointerType()) {
4734
14
      Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4735
14
      ReplaceStmt(S, BlockCall);
4736
14
      return BlockCall;
4737
14
    }
4738
1.78k
  }
4739
1.78k
  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4740
31
    RewriteCastExpr(CE);
4741
31
  }
4742
#if 0
4743
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4744
    CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4745
                                                   ICE->getSubExpr(),
4746
                                                   SourceLocation());
4747
    // Get the new text.
4748
    std::string SStr;
4749
    llvm::raw_string_ostream Buf(SStr);
4750
    Replacement->printPretty(Buf);
4751
    const std::string &Str = Buf.str();
4752
4753
    printf("CAST = %s\n", &Str[0]);
4754
    InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
4755
    delete S;
4756
    return Replacement;
4757
  }
4758
#endif
4759
  // Return this stmt unmodified.
4760
1.78k
  return S;
4761
1.78k
}
4762
4763
11
void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4764
18
  for (auto *FD : RD->fields()) {
4765
18
    if (isTopLevelBlockPointerType(FD->getType()))
4766
0
      RewriteBlockPointerDecl(FD);
4767
18
    if (FD->getType()->isObjCQualifiedIdType() ||
4768
18
        
FD->getType()->isObjCQualifiedInterfaceType()17
)
4769
1
      RewriteObjCQualifiedInterfaceTypes(FD);
4770
18
  }
4771
11
}
4772
4773
/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4774
/// main file of the input.
4775
522
void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4776
522
  switch (D->getKind()) {
4777
522
    case Decl::Function: {
4778
136
      FunctionDecl *FD = cast<FunctionDecl>(D);
4779
136
      if (FD->isOverloadedOperator())
4780
0
        return;
4781
136
4782
136
      // Since function prototypes don't have ParmDecl's, we check the function
4783
136
      // prototype. This enables us to rewrite function declarations and
4784
136
      // definitions using the same code.
4785
136
      RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4786
136
4787
136
      if (!FD->isThisDeclarationADefinition())
4788
72
        break;
4789
64
4790
64
      // FIXME: If this should support Obj-C++, support CXXTryStmt
4791
64
      if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4792
64
        CurFunctionDef = FD;
4793
64
        CurFunctionDeclToDeclareForBlock = FD;
4794
64
        CurrentBody = Body;
4795
64
        Body =
4796
64
        cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4797
64
        FD->setBody(Body);
4798
64
        CurrentBody = nullptr;
4799
64
        if (PropParentMap) {
4800
0
          delete PropParentMap;
4801
0
          PropParentMap = nullptr;
4802
0
        }
4803
64
        // This synthesizes and inserts the block "impl" struct, invoke function,
4804
64
        // and any copy/dispose helper functions.
4805
64
        InsertBlockLiteralsWithinFunction(FD);
4806
64
        CurFunctionDef = nullptr;
4807
64
        CurFunctionDeclToDeclareForBlock = nullptr;
4808
64
      }
4809
64
      break;
4810
64
    }
4811
77
    case Decl::ObjCMethod: {
4812
77
      ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4813
77
      if (CompoundStmt *Body = MD->getCompoundBody()) {
4814
77
        CurMethodDef = MD;
4815
77
        CurrentBody = Body;
4816
77
        Body =
4817
77
          cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4818
77
        MD->setBody(Body);
4819
77
        CurrentBody = nullptr;
4820
77
        if (PropParentMap) {
4821
0
          delete PropParentMap;
4822
0
          PropParentMap = nullptr;
4823
0
        }
4824
77
        InsertBlockLiteralsWithinMethod(MD);
4825
77
        CurMethodDef = nullptr;
4826
77
      }
4827
77
      break;
4828
64
    }
4829
64
    case Decl::ObjCImplementation: {
4830
64
      ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4831
64
      ClassImplementation.push_back(CI);
4832
64
      break;
4833
64
    }
4834
64
    case Decl::ObjCCategoryImpl: {
4835
6
      ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4836
6
      CategoryImplementation.push_back(CI);
4837
6
      break;
4838
64
    }
4839
64
    case Decl::Var: {
4840
17
      VarDecl *VD = cast<VarDecl>(D);
4841
17
      RewriteObjCQualifiedInterfaceTypes(VD);
4842
17
      if (isTopLevelBlockPointerType(VD->getType()))
4843
4
        RewriteBlockPointerDecl(VD);
4844
13
      else if (VD->getType()->isFunctionPointerType()) {
4845
0
        CheckFunctionPointerDecl(VD->getType(), VD);
4846
0
        if (VD->getInit()) {
4847
0
          if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4848
0
            RewriteCastExpr(CE);
4849
0
          }
4850
0
        }
4851
13
      } else if (VD->getType()->isRecordType()) {
4852
0
        RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4853
0
        if (RD->isCompleteDefinition())
4854
0
          RewriteRecordBody(RD);
4855
0
      }
4856
17
      if (VD->getInit()) {
4857
9
        GlobalVarDecl = VD;
4858
9
        CurrentBody = VD->getInit();
4859
9
        RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4860
9
        CurrentBody = nullptr;
4861
9
        if (PropParentMap) {
4862
0
          delete PropParentMap;
4863
0
          PropParentMap = nullptr;
4864
0
        }
4865
9
        SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4866
9
        GlobalVarDecl = nullptr;
4867
9
4868
9
        // This is needed for blocks.
4869
9
        if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4870
0
            RewriteCastExpr(CE);
4871
0
        }
4872
9
      }
4873
17
      break;
4874
64
    }
4875
64
    case Decl::TypeAlias:
4876
50
    case Decl::Typedef: {
4877
50
      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4878
50
        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4879
20
          RewriteBlockPointerDecl(TD);
4880
30
        else if (TD->getUnderlyingType()->isFunctionPointerType())
4881
0
          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4882
50
      }
4883
50
      break;
4884
50
    }
4885
50
    case Decl::CXXRecord:
4886
14
    case Decl::Record: {
4887
14
      RecordDecl *RD = cast<RecordDecl>(D);
4888
14
      if (RD->isCompleteDefinition())
4889
11
        RewriteRecordBody(RD);
4890
14
      break;
4891
14
    }
4892
158
    default:
4893
158
      break;
4894
522
  }
4895
522
  // Nothing yet.
4896
522
}
4897
4898
86
void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4899
86
  if (Diags.hasErrorOccurred())
4900
0
    return;
4901
86
4902
86
  RewriteInclude();
4903
86
4904
86
  // Here's a great place to add any extra declarations that may be needed.
4905
86
  // Write out meta data for each @protocol(<expr>).
4906
86
  for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4907
0
    RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4908
86
4909
86
  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4910
86
  if (ClassImplementation.size() || 
CategoryImplementation.size()33
)
4911
53
    RewriteImplementations();
4912
86
4913
86
  // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
4914
86
  // we are done.
4915
86
  if (const RewriteBuffer *RewriteBuf =
4916
86
      Rewrite.getRewriteBufferFor(MainFileID)) {
4917
86
    //printf("Changed:\n");
4918
86
    *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4919
86
  } else {
4920
0
    llvm::errs() << "No changes\n";
4921
0
  }
4922
86
4923
86
  if (ClassImplementation.size() || 
CategoryImplementation.size()33
||
4924
86
      
ProtocolExprDecls.size()33
) {
4925
53
    // Rewrite Objective-c meta data*
4926
53
    std::string ResultStr;
4927
53
    RewriteMetaDataIntoBuffer(ResultStr);
4928
53
    // Emit metadata.
4929
53
    *OutFile << ResultStr;
4930
53
  }
4931
86
  OutFile->flush();
4932
86
}
4933
4934
86
void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4935
86
  InitializeCommon(context);
4936
86
4937
86
  // declaring objc_selector outside the parameter list removes a silly
4938
86
  // scope related warning...
4939
86
  if (IsHeader)
4940
0
    Preamble = "#pragma once\n";
4941
86
  Preamble += "struct objc_selector; struct objc_class;\n";
4942
86
  Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4943
86
  Preamble += "struct objc_object *superClass; ";
4944
86
  if (LangOpts.MicrosoftExt) {
4945
51
    // Add a constructor for creating temporary objects.
4946
51
    Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4947
51
    ": ";
4948
51
    Preamble += "object(o), superClass(s) {} ";
4949
51
  }
4950
86
  Preamble += "};\n";
4951
86
  Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4952
86
  Preamble += "typedef struct objc_object Protocol;\n";
4953
86
  Preamble += "#define _REWRITER_typedef_Protocol\n";
4954
86
  Preamble += "#endif\n";
4955
86
  if (LangOpts.MicrosoftExt) {
4956
51
    Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4957
51
    Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4958
51
  } else
4959
35
    Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4960
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4961
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4962
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4963
86
  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4964
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4965
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4966
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4967
86
  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4968
86
  Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4969
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4970
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4971
86
  Preamble += "(const char *);\n";
4972
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4973
86
  Preamble += "(struct objc_class *);\n";
4974
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4975
86
  Preamble += "(const char *);\n";
4976
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4977
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4978
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4979
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4980
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4981
86
  Preamble += "(struct objc_class *, struct objc_object *);\n";
4982
86
  // @synchronized hooks.
4983
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4984
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4985
86
  Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4986
86
  Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4987
86
  Preamble += "struct __objcFastEnumerationState {\n\t";
4988
86
  Preamble += "unsigned long state;\n\t";
4989
86
  Preamble += "void **itemsPtr;\n\t";
4990
86
  Preamble += "unsigned long *mutationsPtr;\n\t";
4991
86
  Preamble += "unsigned long extra[5];\n};\n";
4992
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
4993
86
  Preamble += "#define __FASTENUMERATIONSTATE\n";
4994
86
  Preamble += "#endif\n";
4995
86
  Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
4996
86
  Preamble += "struct __NSConstantStringImpl {\n";
4997
86
  Preamble += "  int *isa;\n";
4998
86
  Preamble += "  int flags;\n";
4999
86
  Preamble += "  char *str;\n";
5000
86
  Preamble += "  long length;\n";
5001
86
  Preamble += "};\n";
5002
86
  Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5003
86
  Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5004
86
  Preamble += "#else\n";
5005
86
  Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5006
86
  Preamble += "#endif\n";
5007
86
  Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5008
86
  Preamble += "#endif\n";
5009
86
  // Blocks preamble.
5010
86
  Preamble += "#ifndef BLOCK_IMPL\n";
5011
86
  Preamble += "#define BLOCK_IMPL\n";
5012
86
  Preamble += "struct __block_impl {\n";
5013
86
  Preamble += "  void *isa;\n";
5014
86
  Preamble += "  int Flags;\n";
5015
86
  Preamble += "  int Reserved;\n";
5016
86
  Preamble += "  void *FuncPtr;\n";
5017
86
  Preamble += "};\n";
5018
86
  Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5019
86
  Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5020
86
  Preamble += "extern \"C\" __declspec(dllexport) "
5021
86
  "void _Block_object_assign(void *, const void *, const int);\n";
5022
86
  Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5023
86
  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5024
86
  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5025
86
  Preamble += "#else\n";
5026
86
  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5027
86
  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5028
86
  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5029
86
  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5030
86
  Preamble += "#endif\n";
5031
86
  Preamble += "#endif\n";
5032
86
  if (LangOpts.MicrosoftExt) {
5033
51
    Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5034
51
    Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5035
51
    Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5036
51
    Preamble += "#define __attribute__(X)\n";
5037
51
    Preamble += "#endif\n";
5038
51
    Preamble += "#define __weak\n";
5039
51
  }
5040
35
  else {
5041
35
    Preamble += "#define __block\n";
5042
35
    Preamble += "#define __weak\n";
5043
35
  }
5044
86
  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5045
86
  // as this avoids warning in any 64bit/32bit compilation model.
5046
86
  Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5047
86
}
5048
5049
/// RewriteIvarOffsetComputation - This routine synthesizes computation of
5050
/// ivar offset.
5051
void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5052
57
                                                         std::string &Result) {
5053
57
  if (ivar->isBitField()) {
5054
0
    // FIXME: The hack below doesn't work for bitfields. For now, we simply
5055
0
    // place all bitfields at offset 0.
5056
0
    Result += "0";
5057
57