File: AlignmentAnalysis.cpp

package info (click to toggle)
intel-graphics-compiler2 2.16.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 106,644 kB
  • sloc: cpp: 805,640; lisp: 287,672; ansic: 16,414; python: 3,952; yacc: 2,588; lex: 1,666; pascal: 313; sh: 186; makefile: 35
file content (531 lines) | stat: -rw-r--r-- 19,599 bytes parent folder | download
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2024 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include "AlignmentAnalysis.hpp"
#include "Compiler/IGCPassSupport.h"
#include "Compiler/CodeGenPublic.h"
#include "common/LLVMWarningsPush.hpp"
#include "llvm/IR/InstIterator.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvmWrapper/Support/Alignment.h"
#include "llvmWrapper/IR/Argument.h"
#include "common/LLVMWarningsPop.hpp"
#include <deque>
#include <set>
#include "Probe/Assertion.h"

using namespace llvm;
using namespace IGC;

// Register pass to igc-opt
#define PASS_FLAG "igc-fix-alignment"
#define PASS_DESCRIPTION "Fix argument alignments ad alignments of instructions according to OpenCL rules"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS false
IGC_INITIALIZE_PASS_BEGIN(AlignmentAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_END(AlignmentAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)

char AlignmentAnalysis::ID = 0;

static const Align MinimumAlignment = Align(1);

AlignmentAnalysis::AlignmentAnalysis() : FunctionPass(ID) {
  initializeAlignmentAnalysisPass(*PassRegistry::getPassRegistry());
}

// Check if the function has OpenCL metadata that specifies the alignment of
// its arguments. If it does, set the LLVM alignment attribute of the
// arguments accordingly. This is helpful for passes like InferAlignment.
void AlignmentAnalysis::setArgumentAlignmentBasedOnOptionalMetadata(Function &F) {

  if (F.hasMetadata("kernel_arg_type")) {
    auto EmitOptFailure = [&F](const llvm::Twine &Msg) {
      DiagnosticInfoOptimizationFailure Diag(F, F.getSubprogram(), Msg);
      F.getContext().diagnose(Diag);
    };

    auto *MD = F.getMetadata("kernel_arg_type");
    if (F.arg_size() != MD->getNumOperands()) {
      EmitOptFailure("Mismatch between the number of arguments and the number of "
                     "kernel_arg_type metadata operands in function " +
                     F.getName());
      return;
    }

    for (unsigned OpNumber = 0; OpNumber < MD->getNumOperands(); ++OpNumber) {
      auto *Op = dyn_cast<MDString>(MD->getOperand(OpNumber));
      if (!Op) {
        EmitOptFailure("Expected MDString in kernel_arg_type metadata in "
                       "function " +
                       F.getName());
        return;
      }

      auto *Arg = F.getArg(OpNumber);
      if (!Arg->getType()->isPointerTy())
        continue;

      if (Arg->getParamAlign()) {
        // If the alignment is already set, skip this argument.
        continue;
      }

      if (!Op->getString().endswith("*")) {
        // If the metadata string does not end with '*', skip this argument.
        // This can be e.g. a struct pointer passed byval.
        // DPC++ does not add "*" in this case and we will not be able to
        // set alignment for such arguments.
        return;
      }

      // Remove the trailing '*' from the metadata string
      StringRef KernelArgType = Op->getString().drop_back();

      StringRef ScalarType = KernelArgType.take_until([](char C) { return C >= '0' && C <= '9'; });

      auto ScalarAlignment = llvm::StringSwitch<std::optional<llvm::Align>>(ScalarType)
                                 .CasesLower("char", "uchar", llvm::Align(1))
                                 .CasesLower("short", "ushort", "half", llvm::Align(2))
                                 .CasesLower("int", "uint", "float", llvm::Align(4))
                                 .CasesLower("long", "ulong", "double", llvm::Align(8))
                                 .Default(std::nullopt);

      if (!ScalarAlignment) {
        // If the scalar type is not recognized, skip this argument - this can
        // be e.g. a struct pointer
        continue;
      }

      llvm::Align Alignment = *ScalarAlignment;
      uint64_t VectorSize = 0;
      KernelArgType = KernelArgType.drop_front(ScalarType.size());
      if (!KernelArgType.getAsInteger(10, VectorSize)) {
        if (VectorSize == 3)
          VectorSize = 4;
        Alignment = Align(VectorSize * Alignment.value());
      }
      assert(Alignment.value() && "Alignment should not be zero!");

      Arg->addAttr(llvm::Attribute::getWithAlignment(F.getContext(), Alignment));
    }
  }
}

bool AlignmentAnalysis::runOnFunction(Function &F) {

  setArgumentAlignmentBasedOnOptionalMetadata(F);

  m_DL = &F.getParent()->getDataLayout();

  // The work-list queue for the data flow algorithm
  std::deque<Instruction *> workList;

  // A helper set, to avoid inserting the same instruction
  // into the worklist several times. (this is the set of "grey" nodes).
  // We could instead perform lookups directly on the worklist, but this
  // is faster.
  std::set<Instruction *> inList;

  // First, initialize the worklist with all of the instructions in the function.
  for (llvm::inst_iterator inst = inst_begin(F), instEnd = inst_end(F); inst != instEnd; ++inst) {
    workList.push_back(&*inst);
    inList.insert(&*inst);
  }

  // It is more efficient to handle the earlier instructions first,
  // so we pop from the front.
  while (!inList.empty()) {
    // Get the next instruction
    Instruction *inst = workList.front();
    workList.pop_front();
    inList.erase(inst);

    // Get the alignment of this instruction
    if (processInstruction(inst)) {
      // The alignment of inst changed, (re-)process all users, by
      // adding them to the end of the queue.
      for (auto user = inst->user_begin(), userEnd = inst->user_end(); user != userEnd; ++user) {
        Instruction *userInst = cast<Instruction>(*user);
        // If the user is already in the queue, no need to add it again
        if (inList.find(userInst) == inList.end()) {
          workList.push_back(userInst);
          inList.insert(userInst);
        }
      }
    }
  }

  // in a second step change the alignment for instructions which have improved
  bool Changed = false;
  for (llvm::inst_iterator inst = inst_begin(F), instEnd = inst_end(F); inst != instEnd; ++inst) {
    Changed |= SetInstAlignment(*inst);
  }
  return Changed;
}

Align AlignmentAnalysis::getConstantAlignment(uint64_t C) const {
  if (C == 0) {
    return Align(Value::MaximumAlignment);
  }

  return std::min(Align(Value::MaximumAlignment), Align(1ULL << llvm::countTrailingZeros(C)));
}

Align AlignmentAnalysis::getAlignValue(Value *V) const {
  const Align MinimumAlignmentValue = static_cast<Align>(MinimumAlignment);
  if (isa<Instruction>(V)) {
    auto iter = m_alignmentMap.find(V);
    if (iter == m_alignmentMap.end()) {
      // Instructions are initialize to maximum alignment
      // (this is the "top" value)
      return Align(Value::MaximumAlignment);
    }

    return iter->second;
  } else if (dyn_cast<Constant>(V)) {
    if (ConstantInt *constInt = dyn_cast<ConstantInt>(V)) {
      return getConstantAlignment(constInt->getZExtValue());
    } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
      Align align = GV->getAlign().valueOrOne();

      // If the globalvariable uses the default alignment, pull it from the datalayout
      if (align.value() == 1) {
        return m_DL->getABITypeAlign(GV->getValueType());
      } else {
        return align;
      }
    }

    // Not an int or a globalvariable, be pessimistic.
    return MinimumAlignmentValue;
  } else if (Argument *arg = dyn_cast<Argument>(V)) {
    if (arg->getType()->isPointerTy()) {

      if (arg->hasAttribute(llvm::Attribute::Alignment)) {
        Align align = arg->getParamAlign().valueOrOne();
        // Note that align 1 has no effect on non-byval, non-preallocated arguments.
        if (align.value() != 1 || arg->hasPreallocatedAttr() || arg->hasByValAttr())
          return align;
      }

      Type *pointedTo = IGCLLVM::getArgAttrEltTy(arg);
      if (pointedTo == nullptr && !IGCLLVM::isOpaquePointerTy(arg->getType()))
        pointedTo = IGCLLVM::getNonOpaquePtrEltTy(arg->getType());

      // Pointer arguments are guaranteed to be aligned on the ABI alignment
      if (pointedTo != nullptr && pointedTo->isSized()) {
        return m_DL->getABITypeAlign(pointedTo);
      } else {
        // We have some pointer-to-opaque-types which are not real pointers -
        // this is used to pass things like images around.
        // Apparently, DataLayout being asked about the ABI alignment of opaque types.
        // So, we don't.
        return MinimumAlignmentValue;
      }
    } else {
      // We don't know anything about integer arguments.
      return MinimumAlignmentValue;
    }
  }

  // Be pessimistic
  return MinimumAlignmentValue;
}

bool AlignmentAnalysis::processInstruction(llvm::Instruction *I) {
  // Get the currently known alignment of I.
  Align currAlign = getAlignValue(I);

  // Compute the instruction's alignment
  // using the alignment of the arguments.
  uint64_t newAlign = 0;
  if (I->getType()->isPointerTy()) {
    // If a pointer is specifically given an 'align' field in the MD, use it.
    MDNode *alignmentMD = I->getMetadata("align");
    if (alignmentMD)
      newAlign = mdconst::extract<ConstantInt>(alignmentMD->getOperand(0))->getZExtValue();
  }
  if (!newAlign) {
    newAlign = visit(I).value();
  }

  // The new alignment may not be better than the current one,
  // since we're only allowed to go in one direction in the lattice.
  newAlign = std::min(currAlign.value(), newAlign);

  // If the alignment changed, we want to process the users of this
  // value, so return true. Otherwise, this instruction has stabilized
  // (for now).

  if (newAlign != currAlign.value()) {
    m_alignmentMap[I] = Align(newAlign);
    return true;
  }

  return false;
}

Align AlignmentAnalysis::visitInstruction(Instruction &I) {
  // The safe thing to do for unknown instructions is to return 1.
  return MinimumAlignment;
}

Align AlignmentAnalysis::visitAllocaInst(AllocaInst &I) {
  // Return the alignment of the alloca, which ought to be correct
  Align newAlign = I.getAlign();

  // If the alloca uses the default alignment, pull it from the datalayout
  if (!newAlign.value()) {
    newAlign = m_DL->getABITypeAlign(I.getAllocatedType());
  }

  return newAlign;
}

Align AlignmentAnalysis::visitSelectInst(SelectInst &I) {
  Value *srcTrue = I.getTrueValue();
  Value *srcFalse = I.getFalseValue();

  // In general this should be the GCD, but because we assume we are always aligned on
  // powers of 2, the GCD is the minimum.
  return iSTD::Min(getAlignValue(srcTrue), getAlignValue(srcFalse));
}

Align AlignmentAnalysis::visitPHINode(PHINode &I) {
  Align newAlign = Align(Value::MaximumAlignment);

  // The alignment of a PHI is the minimal alignment of any of the
  // incoming values.
  unsigned numVals = I.getNumIncomingValues();
  for (unsigned int i = 0; i < numVals; ++i) {
    Value *op = I.getIncomingValue(i);
    newAlign = std::min(newAlign, getAlignValue(op));
  }

  return newAlign;
}

bool AlignmentAnalysis::SetInstAlignment(llvm::Instruction &I) {
  if (isa<LoadInst>(I)) {
    return SetInstAlignment(cast<LoadInst>(I));
  } else if (isa<StoreInst>(I)) {
    return SetInstAlignment(cast<StoreInst>(I));
  } else if (isa<MemSetInst>(I)) {
    return SetInstAlignment(cast<MemSetInst>(I));
  } else if (isa<MemCpyInst>(I)) {
    return SetInstAlignment(cast<MemCpyInst>(I));
  } else if (isa<MemMoveInst>(I)) {
    return SetInstAlignment(cast<MemMoveInst>(I));
  }
  return false;
}

bool AlignmentAnalysis::SetInstAlignment(LoadInst &I) {
  // Set the align attribute of the load according to the detected
  // alignment of its operand.
  Align curAlign = I.getAlign();
  Align newAlign = std::max(curAlign, getAlignValue(I.getPointerOperand()));
  I.setAlignment(newAlign);
  return curAlign != newAlign;
}

bool AlignmentAnalysis::SetInstAlignment(StoreInst &I) {
  // Set the align attribute of the store according to the detected
  // alignment of its operand.
  Align curAlign = I.getAlign();
  Align newAlign = std::max(I.getAlign(), getAlignValue(I.getPointerOperand()));
  I.setAlignment(newAlign);
  return curAlign != newAlign;
}

Align AlignmentAnalysis::visitAdd(BinaryOperator &I) {
  // Addition can not improve the alignment.
  // In a more precise analysis, it could (e.g. 3 + 1 = 4)
  // but here, we only keep track of the highest power of 2
  // factor.
  // So, the best case scenario is that the alignment stays
  // the same if you add two values with the same alignment.
  // Note that it can not grow even in this case, because
  // we keep an underapproximation. That is:
  // If we know x and y were divisible by 4 but *not* 8,
  // then x + y would be divisible by 8. However, if x is divisible by 4
  // and y is divisible by 8, then x + y is only divisible by 4.
  Value *op0 = I.getOperand(0);
  Value *op1 = I.getOperand(1);

  return iSTD::Min(getAlignValue(op0), getAlignValue(op1));
}

Align AlignmentAnalysis::visitMul(BinaryOperator &I) {
  // Because we are dealing with powers of 2,
  // align(x * y) = align(x) * align(y)
  Value *op0 = I.getOperand(0);
  Value *op1 = I.getOperand(1);

  return Align(assumeAligned(
      std::min(Value::MaximumAlignment, SaturatingMultiply(getAlignValue(op0).value(), getAlignValue(op1).value()))));
}

Align AlignmentAnalysis::visitShl(BinaryOperator &I) {
  // If we are shifting left by a constant, we know the
  // alignment improves according to that value.
  // In any case, it can not drop.
  Value *op0 = I.getOperand(0);
  Value *op1 = I.getOperand(1);

  if (ConstantInt *constOp1 = dyn_cast<ConstantInt>(op1)) {
    auto oldAlignVal = getAlignValue(op0).value();
    IGC_ASSERT_MESSAGE(oldAlignVal, "Alignment should not be zero!");
    uint64_t shiftVal = constOp1->getZExtValue();
    if (shiftVal >= std::numeric_limits<uint64_t>::digits) {
      // This means that the shl will overflow, so we should return the maximum
      // alignment.
      return Align(Value::MaximumAlignment);
    }

    auto newAlignVal = SaturatingMultiply(oldAlignVal, (uint64_t)1 << shiftVal);
    return Align(assumeAligned(std::min(Value::MaximumAlignment, newAlignVal)));
  } else {
    return getAlignValue(op0);
  }
}

Align AlignmentAnalysis::visitAnd(BinaryOperator &I) {
  Value *op0 = I.getOperand(0);
  Value *op1 = I.getOperand(1);

  // If one of the operands has trailing zeroes up to some point,
  // then so will the result. So, the alignment is at least the maximum
  // of the operands.
  return iSTD::Max(getAlignValue(op0), getAlignValue(op1));
}

Align AlignmentAnalysis::visitGetElementPtrInst(GetElementPtrInst &I) {
  // The alignment can never be better than the alignment of the base pointer
  Align newAlign = getAlignValue(I.getPointerOperand());

  gep_type_iterator GTI = gep_type_begin(&I);
  for (auto op = I.op_begin() + 1, opE = I.op_end(); op != opE; ++op, ++GTI) {
    uint64_t offset = 0;
    if (StructType *StTy = GTI.getStructTypeOrNull()) {
      auto Field = static_cast<unsigned>((cast<Constant>(*op))->getUniqueInteger().getZExtValue());
      offset = static_cast<uint64_t>(m_DL->getStructLayout(StTy)->getElementOffset(Field));
    } else {
      Type *Ty = GTI.getIndexedType();
      auto multiplier = static_cast<uint64_t>(m_DL->getTypeAllocSize(Ty));
      offset = multiplier * getAlignValue(*op).value();
    }

    // It's possible offset is not a power of 2, because struct fields
    // may be aligned on all sorts of weird values. So we can not just
    // take the minimum between newAlign and offset, we need the
    // highest power of 2 that divides both.

    // x | y has trailing 0s exactly where both x and y have trailing 0s.
    newAlign = getConstantAlignment(newAlign.value() | offset);
  }

  return newAlign;
}

// Casts don't change the alignment.
// Technically we could do better (a trunc or an extend may improve alignment)
// but this doesn't seem important enough.
Align AlignmentAnalysis::visitBitCastInst(BitCastInst &I) { return getAlignValue(I.getOperand(0)); }

Align AlignmentAnalysis::visitPtrToIntInst(PtrToIntInst &I) { return getAlignValue(I.getOperand(0)); }

Align AlignmentAnalysis::visitIntToPtrInst(IntToPtrInst &I) { return getAlignValue(I.getOperand(0)); }

Align AlignmentAnalysis::visitTruncInst(TruncInst &I) { return getAlignValue(I.getOperand(0)); }

Align AlignmentAnalysis::visitZExtInst(ZExtInst &I) { return getAlignValue(I.getOperand(0)); }

Align AlignmentAnalysis::visitSExtInst(SExtInst &I) { return getAlignValue(I.getOperand(0)); }

Align AlignmentAnalysis::visitCallInst(CallInst &I) {
  // Handle alignment for memcpy and memset
  Function *callee = I.getCalledFunction();
  // Skip indirect call!
  if (!callee)
    // return value does not matter
    return MinimumAlignment;

  MemIntrinsic *memIntr = dyn_cast<MemIntrinsic>(&I);
  if (!memIntr)
    return MinimumAlignment;

  Align alignment = MinimumAlignment;
  llvm::Intrinsic::ID ID = memIntr->getIntrinsicID();

  if (ID == Intrinsic::memcpy) {
    MemCpyInst *memCpy = dyn_cast<MemCpyInst>(&I);
    IGC_ASSERT(memCpy);
    if (memCpy) {
      alignment =
          Align(std::min(memCpy->getDestAlign().valueOrOne().value(), memCpy->getSourceAlign().valueOrOne().value()));
    }
  } else if (ID == Intrinsic::memset) {
    alignment = Align(std::max(memIntr->getDestAlign().valueOrOne(), MinimumAlignment));
  }

  return alignment;
}

bool AlignmentAnalysis::SetInstAlignment(MemSetInst &I) {
  // Set the align attribute of the memset according to the detected
  // alignment of its operand.
  auto curAlign = I.getDestAlign();
  Align alignment = std::max(IGCLLVM::getDestAlign(I), getAlignValue(I.getRawDest()));
  I.setDestAlignment(alignment);
  return curAlign != alignment;
}

bool AlignmentAnalysis::SetInstAlignment(MemCpyInst &I) {
  std::function<bool(Value *)> isConstGlobalZero = [&](Value *V) {
    if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
      return isConstGlobalZero(GEP->getPointerOperand());

    if (auto *GV = dyn_cast<GlobalVariable>(V)) {
      if (!GV->isConstant())
        return false;

      if (auto *initializer = GV->getInitializer())
        return initializer->isZeroValue();
    }

    return false;
  };

  MaybeAlign curAlign = I.getDestAlign();

  // If memcpy source is zeroinitialized constant global, memcpy is equivalent to memset to zero.
  // In this case, we can set the alignment of memcpy to the alignment of its destination only.
  if (isConstGlobalZero(I.getRawSource())) {
    Align alignment = std::max(IGCLLVM::getDestAlign(I), getAlignValue(I.getRawDest()));
    I.setDestAlignment(alignment);
    return curAlign != alignment;
  }

  // Set the align attribute of the memcpy based on the minimum alignment of its source and dest fields
  Align minRawAlignment = std::min(getAlignValue(I.getRawDest()), getAlignValue(I.getRawSource()));
  Align alignment = std::max(IGCLLVM::getDestAlign(I), minRawAlignment);
  I.setDestAlignment(alignment);
  return curAlign != alignment;
}

bool AlignmentAnalysis::SetInstAlignment(MemMoveInst &I) {
  // Set the align attribute of the memmove based on the minimum alignment of its source and dest fields
  Align minRawAlignment = std::min(getAlignValue(I.getRawDest()), getAlignValue(I.getRawSource()));
  Align alignment = std::max(IGCLLVM::getDestAlign(I), minRawAlignment);
  MaybeAlign curAlign = I.getDestAlign();
  I.setDestAlignment(alignment);
  return curAlign != alignment;
}