summaryrefslogtreecommitdiffstats
path: root/llvm/pass/CombineCasts.cpp
blob: 71a74ff7e3ce81116534687575082f7fa9a210cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
 *  (C) 2015 by Computer System Laboratory, IIS, Academia Sinica, Taiwan.
 *      See COPYRIGHT in top-level directory.
 */

#include "llvm/Transforms/Utils/Local.h"
#include "llvm-target.h"
#include "llvm-opc.h"
#include "llvm-pass.h"
#include "utils.h"

#define PASS_NAME "CombineCasts"

/*
 * CombineCasts Pass
 */
class CombineCasts : public FunctionPass {
    IRFactory *IF;
    const DataLayout *DL;
    MDFactory *MF;
    IntegerType *Int8Ty;
    IntegerType *Int32Ty;
    IntegerType *Int64Ty;
    IntegerType *IntPtrTy;
    PointerType *Int8PtrTy;
    PointerType *Int32PtrTy;
    PointerType *Int64PtrTy;
    Type *FloatTy;
    Type *DoubleTy;
    IVec toErase;

public:
    static char ID;
    explicit CombineCasts() : FunctionPass(ID) {}
    explicit CombineCasts(IRFactory *IF)
        : FunctionPass(ID), IF(IF), DL(IF->getDL()), MF(IF->getMDFactory())
    {
        LLVMContext &Context = IF->getContext();;
        Int8Ty      = IntegerType::get(Context, 8);
        Int32Ty     = IntegerType::get(Context, 32);
        Int64Ty     = IntegerType::get(Context, 64);
        IntPtrTy    = DL->getIntPtrType(Context);
        Int8PtrTy   = Type::getInt8PtrTy(Context, 0);
        Int32PtrTy  = Type::getInt32PtrTy(Context, 0);
        Int64PtrTy  = Type::getInt64PtrTy(Context, 0);
        FloatTy     = Type::getFloatTy(Context);
        DoubleTy    = Type::getDoubleTy(Context);
    }

    Instruction *getUniqueUser(Instruction *I) {
        if (I->hasOneUse())
            return I->user_back();
        return nullptr;
    };

    bool combineLoadCast(LoadInst *LI);
    bool combineStoreCast(StoreInst *SI);
    bool combineCastCast(Function &F);
    bool simplifySignChange(Function &F);
    bool runOnFunction(Function &F);
};

char CombineCasts::ID = 0;
INITIALIZE_PASS(CombineCasts, "combinecast",
        "Combine bitcast with guest memory loads/stores", false, false)

FunctionPass *llvm::createCombineCasts(IRFactory *IF) 
{
    return new CombineCasts(IF);
}

static bool hasSameCastingTy(ArrayRef<BitCastInst *> IL) {
    Type *SrcTy = IL[0]->getSrcTy();
    Type *DstTy = IL[0]->getDestTy();
    for (BitCastInst *I : IL) {
        if (I->getSrcTy() != SrcTy)
            return false;
        if (I->getDestTy() != DstTy)
            return false;
    }
    return true;
}

/* This function aims to change the load type if (1) the type of loaded data is
 * casted to another type, (2) only one user of the load instruction is bitcast,
 * and (3) all other users of the load instruction are stores.
 *
 * For example:
 *  %0 = load <typeA>*              %0 = load <typeB>*
 *  %1 = bitcast %0, <typeB>        %1 = bitcast %0, <typeA>
 *
 *  %2 = op <typeB> %1, ...    =>   %2 = op <typeB> %0, ...
 *
 *  store %0, <typeA>*              store %1, <typeA>*
 *  store %1, <typeB>*              store %0, <typeB>*
 */
bool CombineCasts::combineLoadCast(LoadInst *LI)
{
    Instruction *Ptr = dyn_cast<Instruction>(LI->getPointerOperand());

    if (!Ptr)
        return false;

    /* Find all bitcast users of this load. */
    SmallVector<BitCastInst *, 4> BCIs;
    for (User *U : LI->users()) {
        Instruction *UI = cast<Instruction>(U);
        switch (UI->getOpcode()) {
        default:
            return false;
        case Instruction::PHI:
        case Instruction::Load:
        case Instruction::Store:
            break;
        case Instruction::BitCast:
            BCIs.push_back(cast<BitCastInst>(UI));
            break;
        }
    }

    if (BCIs.empty() || !hasSameCastingTy(BCIs))
        return false;

    Instruction *InsertPos = LI;
    unsigned Alignment = LI->getAlignment();
    unsigned Volatile = LI->isVolatile();
    Type *SrcTy = LI->getType();
    Type *DstTy = BCIs[0]->getDestTy();

    Type *PtrTy = PointerType::get(DstTy, LI->getPointerAddressSpace());
    if (isa<IntToPtrInst>(Ptr))
        Ptr = new IntToPtrInst(Ptr->getOperand(0), PtrTy, "", InsertPos);
    else
        Ptr = new BitCastInst(Ptr, PtrTy, "", InsertPos);

    Instruction *NewLI = new LoadInst(Ptr, "", Volatile, Alignment, InsertPos);
    Instruction *NewBCI = new BitCastInst(NewLI, SrcTy, "", InsertPos);

    if (MF->isGuestMemory(LI))
        MF->setGuestMemory(NewLI);
    for (BitCastInst *BCI : BCIs)
        BCI->replaceAllUsesWith(NewLI);
    LI->replaceAllUsesWith(NewBCI);

    toErase.push_back(LI);
    for (BitCastInst *BCI : BCIs)
        toErase.push_back(BCI);

    return true;
}

/* This function aims to change the store type if stored data is casted from
 * another type.
 *
 * For example:
 *  %0 = <typeA>
 *  %1 = bitcast %0, <typeB>   =>   store %0, <typeA>*
 *  store %1, <typeB>*
 */
bool CombineCasts::combineStoreCast(StoreInst *SI)
{
    Instruction *Ptr = dyn_cast<Instruction>(SI->getPointerOperand());
    Instruction *Data = dyn_cast<Instruction>(SI->getValueOperand());

    if (!Ptr || !Data || !isa<BitCastInst>(Data))
        return false;

    Instruction *InsertPos = SI;
    unsigned Alignment = SI->getAlignment();
    unsigned Volatile = SI->isVolatile();
    BitCastInst *BCI = cast<BitCastInst>(Data);
    Value *V = BCI->getOperand(0);
    Type *SrcTy = V->getType();

    Type *PtrTy = PointerType::get(SrcTy, SI->getPointerAddressSpace());
    if (isa<IntToPtrInst>(Ptr))
        Ptr = new IntToPtrInst(Ptr->getOperand(0), PtrTy, "", InsertPos);
    else
        Ptr = new BitCastInst(Ptr, PtrTy, "", InsertPos);

    Instruction *NewSI = new StoreInst(V, Ptr, Volatile, Alignment, InsertPos);

    if (MF->isGuestMemory(SI))
        MF->setGuestMemory(NewSI);

    toErase.push_back(SI);
    return true;
}

/* This function aims to eliminate redundant casts.
 * For example:
 *  %0 = <typeA>                   %0 = <typeA>
 *  %1 = bitcast %0, <typeB>  =>
 *  %2 = bitcast %1, <typeC>       %2 = bitcast %0, <typeC>
 *     = op <typeC> %2, ...           = op <typeC> %2, ...
 *
 * And if <typeA> is the same as <typeC>, the code is further optimized to
 *  %0 = <typeA>                   %0 = <typeA>
 *  %1 = bitcast %0, <typeB>  =>
 *  %2 = bitcast %1, <typeC>
 *     = op <typeC> %2, ...           = op <typeA> %0, ...
 */
bool CombineCasts::combineCastCast(Function &F)
{
    SmallVector<Instruction*, 4> Worklist;
    for (auto II = inst_begin(F), EE = inst_end(F); II != EE; II++) {
        Instruction *I = &*II;
        if (isa<BitCastInst>(I))
            Worklist.push_back(I);
    }

    for (auto I : Worklist) {
        BitCastInst *CI = cast<BitCastInst>(I);
        BitCastInst *CSrc = dyn_cast<BitCastInst>(CI->getOperand(0));
        if (!CSrc)
            continue;

        Type *SrcTy = CSrc->getOperand(0)->getType();
        Type *DstTy = CI->getType();
        Value *Result = (SrcTy == DstTy) ? CSrc->getOperand(0) :
            new BitCastInst(CSrc->getOperand(0), CI->getType(), "", CI);
        I->replaceAllUsesWith(Result);
        toErase.push_back(I);
    }

    if (toErase.empty())
        return false;

    ProcessErase(toErase);
    return true;
}

/* This function converts sign change of float/double data (i.e., -num),
 * which is implemented with integer operations, to use float/double ops.
 * For example:
 *  %0 = bitcast float %num to i32
 *  %1 = xor i32 %0, 0x80000000       =>    %0 = fsub float 0, %num
 *  %2 = bitcast %1, float
 */
bool CombineCasts::simplifySignChange(Function &F)
{
    SmallVector<BitCastInst*, 16> Worklist;

    for (auto II = inst_begin(F), EE = inst_end(F); II != EE; II++) {
        Instruction *I = &*II;
        if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
            Type *SrcTy = BCI->getSrcTy();
            Type *DstTy = BCI->getDestTy();
            if (SrcTy == FloatTy && DstTy == Int32Ty)
                Worklist.push_back(BCI);
            else if (SrcTy == DoubleTy && DstTy == Int64Ty)
                Worklist.push_back(BCI);
        }
    }

    for (auto I : Worklist) {
        Type *Ty = I->getSrcTy();
        Value *C = (Ty == FloatTy) ? CONST32(0x80000000)
                                   : CONST64(0x8000000000000000LL);

        /* Check whether the single user of this bitcast is Xor. */
        Instruction *UI = getUniqueUser(I);
        if (UI && UI->getOpcode() == Instruction::Xor && UI->getOperand(1) == C) {
            /* Check whether the single user of this Xor is a bitcast
             * instruction that casts the type back to the src type. */
            Instruction *UUI = getUniqueUser(UI);
            if (UUI && UUI->getOpcode() == Instruction::BitCast &&
                cast<BitCastInst>(UUI)->getDestTy() == Ty) {
                Value *V = BinaryOperator::Create(Instruction::FSub,
                                                  ConstantFP::get(Ty, 0),
                                                  I->getOperand(0), "", I);
                UUI->replaceAllUsesWith(V);
                toErase.push_back(UUI);
            }
        }
    }

    if (toErase.empty())
        return false;

    ProcessErase(toErase);
    return true;
}

bool CombineCasts::runOnFunction(Function &F)
{
    bool Changed = false;
    SmallVector<LoadInst *, 16> Loads;
    SmallVector<StoreInst *, 16> Stores;

    /* Collect all guest memory and non-volatile cpu state loads/stores. */
    for (auto II = inst_begin(F), EE = inst_end(F); II != EE; II++) {
        Instruction *I = &*II;

        if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
            if (MF->isGuestMemory(LI) || !LI->isVolatile())
                Loads.push_back(LI);
        } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
            if (MF->isGuestMemory(SI) || !SI->isVolatile())
                Stores.push_back(SI);
        }
    }

    for (auto LI : Loads)
        Changed |= combineLoadCast(LI);
    for (auto SI : Stores)
        Changed |= combineStoreCast(SI);

    if (toErase.size())
        ProcessErase(toErase);

    Changed |= combineCastCast(F);
    Changed |= simplifySignChange(F);

    return Changed;
}

/*
 * vim: ts=8 sts=4 sw=4 expandtab
 */

OpenPOWER on IntegriCloud