1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the auto-upgrade helper functions.
11 // This is where deprecated IR intrinsics and other IR features are updated to
12 // current specifications.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CFG.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DIBuilder.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instruction.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Regex.h"
31 #include <cstring>
32 using namespace llvm;
33 
34 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
35 
36 // Upgrade the declarations of the SSE4.1 functions whose arguments have
37 // changed their type from v4f32 to v2i64.
38 static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID,
39                                  Function *&NewFn) {
40   // Check whether this is an old version of the function, which received
41   // v4f32 arguments.
42   Type *Arg0Type = F->getFunctionType()->getParamType(0);
43   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
44     return false;
45 
46   // Yes, it's old, replace it with new version.
47   rename(F);
48   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
49   return true;
50 }
51 
52 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
53 // arguments have changed their type from i32 to i8.
54 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
55                                              Function *&NewFn) {
56   // Check that the last argument is an i32.
57   Type *LastArgType = F->getFunctionType()->getParamType(
58      F->getFunctionType()->getNumParams() - 1);
59   if (!LastArgType->isIntegerTy(32))
60     return false;
61 
62   // Move this function aside and map down.
63   rename(F);
64   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
65   return true;
66 }
67 
68 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
69   assert(F && "Illegal to upgrade a non-existent Function.");
70 
71   // Quickly eliminate it, if it's not a candidate.
72   StringRef Name = F->getName();
73   if (Name.size() <= 8 || !Name.startswith("llvm."))
74     return false;
75   Name = Name.substr(5); // Strip off "llvm."
76 
77   switch (Name[0]) {
78   default: break;
79   case 'a': {
80     if (Name.startswith("arm.neon.vclz")) {
81       Type* args[2] = {
82         F->arg_begin()->getType(),
83         Type::getInt1Ty(F->getContext())
84       };
85       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
86       // the end of the name. Change name from llvm.arm.neon.vclz.* to
87       //  llvm.ctlz.*
88       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
89       NewFn = Function::Create(fType, F->getLinkage(),
90                                "llvm.ctlz." + Name.substr(14), F->getParent());
91       return true;
92     }
93     if (Name.startswith("arm.neon.vcnt")) {
94       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
95                                         F->arg_begin()->getType());
96       return true;
97     }
98     Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
99     if (vldRegex.match(Name)) {
100       auto fArgs = F->getFunctionType()->params();
101       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
102       // Can't use Intrinsic::getDeclaration here as the return types might
103       // then only be structurally equal.
104       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
105       NewFn = Function::Create(fType, F->getLinkage(),
106                                "llvm." + Name + ".p0i8", F->getParent());
107       return true;
108     }
109     Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
110     if (vstRegex.match(Name)) {
111       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
112                                                 Intrinsic::arm_neon_vst2,
113                                                 Intrinsic::arm_neon_vst3,
114                                                 Intrinsic::arm_neon_vst4};
115 
116       static const Intrinsic::ID StoreLaneInts[] = {
117         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
118         Intrinsic::arm_neon_vst4lane
119       };
120 
121       auto fArgs = F->getFunctionType()->params();
122       Type *Tys[] = {fArgs[0], fArgs[1]};
123       if (Name.find("lane") == StringRef::npos)
124         NewFn = Intrinsic::getDeclaration(F->getParent(),
125                                           StoreInts[fArgs.size() - 3], Tys);
126       else
127         NewFn = Intrinsic::getDeclaration(F->getParent(),
128                                           StoreLaneInts[fArgs.size() - 5], Tys);
129       return true;
130     }
131     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
132       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
133       return true;
134     }
135     break;
136   }
137 
138   case 'c': {
139     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
140       rename(F);
141       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
142                                         F->arg_begin()->getType());
143       return true;
144     }
145     if (Name.startswith("cttz.") && F->arg_size() == 1) {
146       rename(F);
147       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
148                                         F->arg_begin()->getType());
149       return true;
150     }
151     break;
152   }
153   case 'i': {
154     if (Name.startswith("invariant.start")) {
155       auto Args = F->getFunctionType()->params();
156       Type* ObjectPtr[1] = {Args[1]};
157       if (F->getName() !=
158           Intrinsic::getName(Intrinsic::invariant_start, ObjectPtr)) {
159         rename(F);
160         NewFn = Intrinsic::getDeclaration(
161             F->getParent(), Intrinsic::invariant_start, ObjectPtr);
162         return true;
163       }
164     }
165     if (Name.startswith("invariant.end")) {
166       auto Args = F->getFunctionType()->params();
167       Type* ObjectPtr[1] = {Args[2]};
168       if (F->getName() !=
169           Intrinsic::getName(Intrinsic::invariant_end, ObjectPtr)) {
170         rename(F);
171         NewFn = Intrinsic::getDeclaration(F->getParent(),
172                                           Intrinsic::invariant_end, ObjectPtr);
173         return true;
174       }
175     }
176     break;
177   }
178   case 'm': {
179     if (Name.startswith("masked.load.")) {
180       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
181       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
182         rename(F);
183         NewFn = Intrinsic::getDeclaration(F->getParent(),
184                                           Intrinsic::masked_load,
185                                           Tys);
186         return true;
187       }
188     }
189     if (Name.startswith("masked.store.")) {
190       auto Args = F->getFunctionType()->params();
191       Type *Tys[] = { Args[0], Args[1] };
192       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
193         rename(F);
194         NewFn = Intrinsic::getDeclaration(F->getParent(),
195                                           Intrinsic::masked_store,
196                                           Tys);
197         return true;
198       }
199     }
200     break;
201   }
202 
203   case 'o':
204     // We only need to change the name to match the mangling including the
205     // address space.
206     if (F->arg_size() == 2 && Name.startswith("objectsize.")) {
207       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
208       if (F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
209         rename(F);
210         NewFn = Intrinsic::getDeclaration(F->getParent(),
211                                           Intrinsic::objectsize, Tys);
212         return true;
213       }
214     }
215     break;
216 
217   case 's':
218     if (Name == "stackprotectorcheck") {
219       NewFn = nullptr;
220       return true;
221     }
222     break;
223 
224   case 'x': {
225     bool IsX86 = Name.startswith("x86.");
226     if (IsX86)
227       Name = Name.substr(4);
228 
229     if (IsX86 &&
230         (Name.startswith("sse2.pcmpeq.") ||
231          Name.startswith("sse2.pcmpgt.") ||
232          Name.startswith("avx2.pcmpeq.") ||
233          Name.startswith("avx2.pcmpgt.") ||
234          Name.startswith("avx512.mask.pcmpeq.") ||
235          Name.startswith("avx512.mask.pcmpgt.") ||
236          Name == "sse41.pmaxsb" ||
237          Name == "sse2.pmaxs.w" ||
238          Name == "sse41.pmaxsd" ||
239          Name == "sse2.pmaxu.b" ||
240          Name == "sse41.pmaxuw" ||
241          Name == "sse41.pmaxud" ||
242          Name == "sse41.pminsb" ||
243          Name == "sse2.pmins.w" ||
244          Name == "sse41.pminsd" ||
245          Name == "sse2.pminu.b" ||
246          Name == "sse41.pminuw" ||
247          Name == "sse41.pminud" ||
248          Name == "avx512.mask.pshuf.b.128" ||
249          Name == "avx512.mask.pshuf.b.256" ||
250          Name.startswith("avx2.pmax") ||
251          Name.startswith("avx2.pmin") ||
252          Name.startswith("avx512.mask.pmax") ||
253          Name.startswith("avx512.mask.pmin") ||
254          Name.startswith("avx2.vbroadcast") ||
255          Name.startswith("avx2.pbroadcast") ||
256          Name.startswith("avx.vpermil.") ||
257          Name.startswith("sse2.pshuf") ||
258          Name.startswith("avx512.pbroadcast") ||
259          Name.startswith("avx512.mask.broadcast.s") ||
260          Name.startswith("avx512.mask.movddup") ||
261          Name.startswith("avx512.mask.movshdup") ||
262          Name.startswith("avx512.mask.movsldup") ||
263          Name.startswith("avx512.mask.pshuf.d.") ||
264          Name.startswith("avx512.mask.pshufl.w.") ||
265          Name.startswith("avx512.mask.pshufh.w.") ||
266          Name.startswith("avx512.mask.shuf.p") ||
267          Name.startswith("avx512.mask.vpermil.p") ||
268          Name.startswith("avx512.mask.perm.df.") ||
269          Name.startswith("avx512.mask.perm.di.") ||
270          Name.startswith("avx512.mask.punpckl") ||
271          Name.startswith("avx512.mask.punpckh") ||
272          Name.startswith("avx512.mask.unpckl.") ||
273          Name.startswith("avx512.mask.unpckh.") ||
274          Name.startswith("avx512.mask.pand.") ||
275          Name.startswith("avx512.mask.pandn.") ||
276          Name.startswith("avx512.mask.por.") ||
277          Name.startswith("avx512.mask.pxor.") ||
278          Name.startswith("avx512.mask.and.") ||
279          Name.startswith("avx512.mask.andn.") ||
280          Name.startswith("avx512.mask.or.") ||
281          Name.startswith("avx512.mask.xor.") ||
282          Name.startswith("avx512.mask.padd.") ||
283          Name.startswith("avx512.mask.psub.") ||
284          Name.startswith("avx512.mask.pmull.") ||
285          Name == "avx512.mask.add.pd.128" ||
286          Name == "avx512.mask.add.pd.256" ||
287          Name == "avx512.mask.add.ps.128" ||
288          Name == "avx512.mask.add.ps.256" ||
289          Name == "avx512.mask.div.pd.128" ||
290          Name == "avx512.mask.div.pd.256" ||
291          Name == "avx512.mask.div.ps.128" ||
292          Name == "avx512.mask.div.ps.256" ||
293          Name == "avx512.mask.mul.pd.128" ||
294          Name == "avx512.mask.mul.pd.256" ||
295          Name == "avx512.mask.mul.ps.128" ||
296          Name == "avx512.mask.mul.ps.256" ||
297          Name == "avx512.mask.sub.pd.128" ||
298          Name == "avx512.mask.sub.pd.256" ||
299          Name == "avx512.mask.sub.ps.128" ||
300          Name == "avx512.mask.sub.ps.256" ||
301          Name.startswith("avx512.mask.psll.d") ||
302          Name.startswith("avx512.mask.psll.q") ||
303          Name.startswith("avx512.mask.psll.w") ||
304          Name.startswith("avx512.mask.psra.d") ||
305          Name.startswith("avx512.mask.psra.q") ||
306          Name.startswith("avx512.mask.psra.w") ||
307          Name.startswith("avx512.mask.psrl.d") ||
308          Name.startswith("avx512.mask.psrl.q") ||
309          Name.startswith("avx512.mask.psrl.w") ||
310          Name.startswith("avx512.mask.pslli") ||
311          Name.startswith("avx512.mask.psrai") ||
312          Name.startswith("avx512.mask.psrli") ||
313          Name == "avx512.mask.psllv2.di" ||
314          Name == "avx512.mask.psllv4.di" ||
315          Name == "avx512.mask.psllv4.si" ||
316          Name == "avx512.mask.psllv8.si" ||
317          Name == "avx512.mask.psrav4.si" ||
318          Name == "avx512.mask.psrav8.si" ||
319          Name == "avx512.mask.psrlv2.di" ||
320          Name == "avx512.mask.psrlv4.di" ||
321          Name == "avx512.mask.psrlv4.si" ||
322          Name == "avx512.mask.psrlv8.si" ||
323          Name.startswith("avx512.mask.psllv.") ||
324          Name.startswith("avx512.mask.psrav.") ||
325          Name.startswith("avx512.mask.psrlv.") ||
326          Name.startswith("sse41.pmovsx") ||
327          Name.startswith("sse41.pmovzx") ||
328          Name.startswith("avx2.pmovsx") ||
329          Name.startswith("avx2.pmovzx") ||
330          Name.startswith("avx512.mask.pmovsx") ||
331          Name.startswith("avx512.mask.pmovzx") ||
332          Name == "sse2.cvtdq2pd" ||
333          Name == "sse2.cvtps2pd" ||
334          Name == "avx.cvtdq2.pd.256" ||
335          Name == "avx.cvt.ps2.pd.256" ||
336          Name.startswith("avx.vinsertf128.") ||
337          Name == "avx2.vinserti128" ||
338          Name.startswith("avx.vextractf128.") ||
339          Name == "avx2.vextracti128" ||
340          Name.startswith("sse4a.movnt.") ||
341          Name.startswith("avx.movnt.") ||
342          Name.startswith("avx512.storent.") ||
343          Name == "sse2.storel.dq" ||
344          Name.startswith("sse.storeu.") ||
345          Name.startswith("sse2.storeu.") ||
346          Name.startswith("avx.storeu.") ||
347          Name.startswith("avx512.mask.storeu.") ||
348          Name.startswith("avx512.mask.store.p") ||
349          Name.startswith("avx512.mask.store.b.") ||
350          Name.startswith("avx512.mask.store.w.") ||
351          Name.startswith("avx512.mask.store.d.") ||
352          Name.startswith("avx512.mask.store.q.") ||
353          Name.startswith("avx512.mask.loadu.") ||
354          Name.startswith("avx512.mask.load.") ||
355          Name == "sse42.crc32.64.8" ||
356          Name.startswith("avx.vbroadcast.s") ||
357          Name.startswith("avx512.mask.palignr.") ||
358          Name.startswith("sse2.psll.dq") ||
359          Name.startswith("sse2.psrl.dq") ||
360          Name.startswith("avx2.psll.dq") ||
361          Name.startswith("avx2.psrl.dq") ||
362          Name.startswith("avx512.psll.dq") ||
363          Name.startswith("avx512.psrl.dq") ||
364          Name == "sse41.pblendw" ||
365          Name.startswith("sse41.blendp") ||
366          Name.startswith("avx.blend.p") ||
367          Name == "avx2.pblendw" ||
368          Name.startswith("avx2.pblendd.") ||
369          Name.startswith("avx.vbroadcastf128") ||
370          Name == "avx2.vbroadcasti128" ||
371          Name == "xop.vpcmov" ||
372          (Name.startswith("xop.vpcom") && F->arg_size() == 2))) {
373       NewFn = nullptr;
374       return true;
375     }
376     // SSE4.1 ptest functions may have an old signature.
377     if (IsX86 && Name.startswith("sse41.ptest")) {
378       if (Name.substr(11) == "c")
379         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn);
380       if (Name.substr(11) == "z")
381         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn);
382       if (Name.substr(11) == "nzc")
383         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
384     }
385     // Several blend and other instructions with masks used the wrong number of
386     // bits.
387     if (IsX86 && Name == "sse41.insertps")
388       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
389                                               NewFn);
390     if (IsX86 && Name == "sse41.dppd")
391       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
392                                               NewFn);
393     if (IsX86 && Name == "sse41.dpps")
394       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
395                                               NewFn);
396     if (IsX86 && Name == "sse41.mpsadbw")
397       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
398                                               NewFn);
399     if (IsX86 && Name == "avx.dp.ps.256")
400       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
401                                               NewFn);
402     if (IsX86 && Name == "avx2.mpsadbw")
403       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
404                                               NewFn);
405 
406     // frcz.ss/sd may need to have an argument dropped
407     if (IsX86 && Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
408       rename(F);
409       NewFn = Intrinsic::getDeclaration(F->getParent(),
410                                         Intrinsic::x86_xop_vfrcz_ss);
411       return true;
412     }
413     if (IsX86 && Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
414       rename(F);
415       NewFn = Intrinsic::getDeclaration(F->getParent(),
416                                         Intrinsic::x86_xop_vfrcz_sd);
417       return true;
418     }
419     // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
420     if (IsX86 && Name.startswith("xop.vpermil2")) {
421       auto Params = F->getFunctionType()->params();
422       auto Idx = Params[2];
423       if (Idx->getScalarType()->isFloatingPointTy()) {
424         rename(F);
425         unsigned IdxSize = Idx->getPrimitiveSizeInBits();
426         unsigned EltSize = Idx->getScalarSizeInBits();
427         Intrinsic::ID Permil2ID;
428         if (EltSize == 64 && IdxSize == 128)
429           Permil2ID = Intrinsic::x86_xop_vpermil2pd;
430         else if (EltSize == 32 && IdxSize == 128)
431           Permil2ID = Intrinsic::x86_xop_vpermil2ps;
432         else if (EltSize == 64 && IdxSize == 256)
433           Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
434         else
435           Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
436         NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
437         return true;
438       }
439     }
440     break;
441   }
442   }
443 
444   //  This may not belong here. This function is effectively being overloaded
445   //  to both detect an intrinsic which needs upgrading, and to provide the
446   //  upgraded form of the intrinsic. We should perhaps have two separate
447   //  functions for this.
448   return false;
449 }
450 
451 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
452   NewFn = nullptr;
453   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
454   assert(F != NewFn && "Intrinsic function upgraded to the same function");
455 
456   // Upgrade intrinsic attributes.  This does not change the function.
457   if (NewFn)
458     F = NewFn;
459   if (Intrinsic::ID id = F->getIntrinsicID())
460     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
461   return Upgraded;
462 }
463 
464 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
465   // Nothing to do yet.
466   return false;
467 }
468 
469 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
470 // to byte shuffles.
471 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
472                                          Value *Op, unsigned Shift) {
473   Type *ResultTy = Op->getType();
474   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
475 
476   // Bitcast from a 64-bit element type to a byte element type.
477   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
478   Op = Builder.CreateBitCast(Op, VecTy, "cast");
479 
480   // We'll be shuffling in zeroes.
481   Value *Res = Constant::getNullValue(VecTy);
482 
483   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
484   // we'll just return the zero vector.
485   if (Shift < 16) {
486     uint32_t Idxs[64];
487     // 256/512-bit version is split into 2/4 16-byte lanes.
488     for (unsigned l = 0; l != NumElts; l += 16)
489       for (unsigned i = 0; i != 16; ++i) {
490         unsigned Idx = NumElts + i - Shift;
491         if (Idx < NumElts)
492           Idx -= NumElts - 16; // end of lane, switch operand.
493         Idxs[l + i] = Idx + l;
494       }
495 
496     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
497   }
498 
499   // Bitcast back to a 64-bit element type.
500   return Builder.CreateBitCast(Res, ResultTy, "cast");
501 }
502 
503 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
504 // to byte shuffles.
505 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
506                                          unsigned Shift) {
507   Type *ResultTy = Op->getType();
508   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
509 
510   // Bitcast from a 64-bit element type to a byte element type.
511   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
512   Op = Builder.CreateBitCast(Op, VecTy, "cast");
513 
514   // We'll be shuffling in zeroes.
515   Value *Res = Constant::getNullValue(VecTy);
516 
517   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
518   // we'll just return the zero vector.
519   if (Shift < 16) {
520     uint32_t Idxs[64];
521     // 256/512-bit version is split into 2/4 16-byte lanes.
522     for (unsigned l = 0; l != NumElts; l += 16)
523       for (unsigned i = 0; i != 16; ++i) {
524         unsigned Idx = i + Shift;
525         if (Idx >= 16)
526           Idx += NumElts - 16; // end of lane, switch operand.
527         Idxs[l + i] = Idx + l;
528       }
529 
530     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
531   }
532 
533   // Bitcast back to a 64-bit element type.
534   return Builder.CreateBitCast(Res, ResultTy, "cast");
535 }
536 
537 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
538                             unsigned NumElts) {
539   llvm::VectorType *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(),
540                              cast<IntegerType>(Mask->getType())->getBitWidth());
541   Mask = Builder.CreateBitCast(Mask, MaskTy);
542 
543   // If we have less than 8 elements, then the starting mask was an i8 and
544   // we need to extract down to the right number of elements.
545   if (NumElts < 8) {
546     uint32_t Indices[4];
547     for (unsigned i = 0; i != NumElts; ++i)
548       Indices[i] = i;
549     Mask = Builder.CreateShuffleVector(Mask, Mask,
550                                        makeArrayRef(Indices, NumElts),
551                                        "extract");
552   }
553 
554   return Mask;
555 }
556 
557 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
558                             Value *Op0, Value *Op1) {
559   // If the mask is all ones just emit the align operation.
560   if (const auto *C = dyn_cast<Constant>(Mask))
561     if (C->isAllOnesValue())
562       return Op0;
563 
564   Mask = getX86MaskVec(Builder, Mask, Op0->getType()->getVectorNumElements());
565   return Builder.CreateSelect(Mask, Op0, Op1);
566 }
567 
568 static Value *UpgradeX86PALIGNRIntrinsics(IRBuilder<> &Builder,
569                                           Value *Op0, Value *Op1, Value *Shift,
570                                           Value *Passthru, Value *Mask) {
571   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
572 
573   unsigned NumElts = Op0->getType()->getVectorNumElements();
574   assert(NumElts % 16 == 0);
575 
576   // If palignr is shifting the pair of vectors more than the size of two
577   // lanes, emit zero.
578   if (ShiftVal >= 32)
579     return llvm::Constant::getNullValue(Op0->getType());
580 
581   // If palignr is shifting the pair of input vectors more than one lane,
582   // but less than two lanes, convert to shifting in zeroes.
583   if (ShiftVal > 16) {
584     ShiftVal -= 16;
585     Op1 = Op0;
586     Op0 = llvm::Constant::getNullValue(Op0->getType());
587   }
588 
589   uint32_t Indices[64];
590   // 256-bit palignr operates on 128-bit lanes so we need to handle that
591   for (unsigned l = 0; l != NumElts; l += 16) {
592     for (unsigned i = 0; i != 16; ++i) {
593       unsigned Idx = ShiftVal + i;
594       if (Idx >= 16)
595         Idx += NumElts - 16; // End of lane, switch operand.
596       Indices[l + i] = Idx + l;
597     }
598   }
599 
600   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
601                                              makeArrayRef(Indices, NumElts),
602                                              "palignr");
603 
604   return EmitX86Select(Builder, Mask, Align, Passthru);
605 }
606 
607 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
608                                  Value *Ptr, Value *Data, Value *Mask,
609                                  bool Aligned) {
610   // Cast the pointer to the right type.
611   Ptr = Builder.CreateBitCast(Ptr,
612                               llvm::PointerType::getUnqual(Data->getType()));
613   unsigned Align =
614     Aligned ? cast<VectorType>(Data->getType())->getBitWidth() / 8 : 1;
615 
616   // If the mask is all ones just emit a regular store.
617   if (const auto *C = dyn_cast<Constant>(Mask))
618     if (C->isAllOnesValue())
619       return Builder.CreateAlignedStore(Data, Ptr, Align);
620 
621   // Convert the mask from an integer type to a vector of i1.
622   unsigned NumElts = Data->getType()->getVectorNumElements();
623   Mask = getX86MaskVec(Builder, Mask, NumElts);
624   return Builder.CreateMaskedStore(Data, Ptr, Align, Mask);
625 }
626 
627 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
628                                 Value *Ptr, Value *Passthru, Value *Mask,
629                                 bool Aligned) {
630   // Cast the pointer to the right type.
631   Ptr = Builder.CreateBitCast(Ptr,
632                              llvm::PointerType::getUnqual(Passthru->getType()));
633   unsigned Align =
634     Aligned ? cast<VectorType>(Passthru->getType())->getBitWidth() / 8 : 1;
635 
636   // If the mask is all ones just emit a regular store.
637   if (const auto *C = dyn_cast<Constant>(Mask))
638     if (C->isAllOnesValue())
639       return Builder.CreateAlignedLoad(Ptr, Align);
640 
641   // Convert the mask from an integer type to a vector of i1.
642   unsigned NumElts = Passthru->getType()->getVectorNumElements();
643   Mask = getX86MaskVec(Builder, Mask, NumElts);
644   return Builder.CreateMaskedLoad(Ptr, Align, Mask, Passthru);
645 }
646 
647 static Value *upgradeIntMinMax(IRBuilder<> &Builder, CallInst &CI,
648                                ICmpInst::Predicate Pred) {
649   Value *Op0 = CI.getArgOperand(0);
650   Value *Op1 = CI.getArgOperand(1);
651   Value *Cmp = Builder.CreateICmp(Pred, Op0, Op1);
652   Value *Res = Builder.CreateSelect(Cmp, Op0, Op1);
653 
654   if (CI.getNumArgOperands() == 4)
655     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
656 
657   return Res;
658 }
659 
660 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallInst &CI,
661                                    ICmpInst::Predicate Pred) {
662   Value *Op0 = CI.getArgOperand(0);
663   unsigned NumElts = Op0->getType()->getVectorNumElements();
664   Value *Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
665 
666   Value *Mask = CI.getArgOperand(2);
667   const auto *C = dyn_cast<Constant>(Mask);
668   if (!C || !C->isAllOnesValue())
669     Cmp = Builder.CreateAnd(Cmp, getX86MaskVec(Builder, Mask, NumElts));
670 
671   if (NumElts < 8) {
672     uint32_t Indices[8];
673     for (unsigned i = 0; i != NumElts; ++i)
674       Indices[i] = i;
675     for (unsigned i = NumElts; i != 8; ++i)
676       Indices[i] = NumElts + i % NumElts;
677     Cmp = Builder.CreateShuffleVector(Cmp,
678                                       Constant::getNullValue(Cmp->getType()),
679                                       Indices);
680   }
681   return Builder.CreateBitCast(Cmp, IntegerType::get(CI.getContext(),
682                                                      std::max(NumElts, 8U)));
683 }
684 
685 // Replace a masked intrinsic with an older unmasked intrinsic.
686 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallInst &CI,
687                                     Intrinsic::ID IID) {
688   Function *F = CI.getCalledFunction();
689   Function *Intrin = Intrinsic::getDeclaration(F->getParent(), IID);
690   Value *Rep = Builder.CreateCall(Intrin,
691                                  { CI.getArgOperand(0), CI.getArgOperand(1) });
692   return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
693 }
694 
695 
696 /// Upgrade a call to an old intrinsic. All argument and return casting must be
697 /// provided to seamlessly integrate with existing context.
698 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
699   Function *F = CI->getCalledFunction();
700   LLVMContext &C = CI->getContext();
701   IRBuilder<> Builder(C);
702   Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
703 
704   assert(F && "Intrinsic call is not direct?");
705 
706   if (!NewFn) {
707     // Get the Function's name.
708     StringRef Name = F->getName();
709 
710     assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
711     Name = Name.substr(5);
712 
713     bool IsX86 = Name.startswith("x86.");
714     if (IsX86)
715       Name = Name.substr(4);
716 
717     Value *Rep;
718     // Upgrade packed integer vector compare intrinsics to compare instructions.
719     if (IsX86 && (Name.startswith("sse2.pcmpeq.") ||
720                   Name.startswith("avx2.pcmpeq."))) {
721       Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
722                                  "pcmpeq");
723       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
724     } else if (IsX86 && (Name.startswith("sse2.pcmpgt.") ||
725                          Name.startswith("avx2.pcmpgt."))) {
726       Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
727                                   "pcmpgt");
728       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
729     } else if (IsX86 && Name.startswith("avx512.mask.pcmpeq.")) {
730       Rep = upgradeMaskedCompare(Builder, *CI, ICmpInst::ICMP_EQ);
731     } else if (IsX86 && Name.startswith("avx512.mask.pcmpgt.")) {
732       Rep = upgradeMaskedCompare(Builder, *CI, ICmpInst::ICMP_SGT);
733     } else if (IsX86 && (Name == "sse41.pmaxsb" ||
734                          Name == "sse2.pmaxs.w" ||
735                          Name == "sse41.pmaxsd" ||
736                          Name.startswith("avx2.pmaxs") ||
737                          Name.startswith("avx512.mask.pmaxs"))) {
738       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SGT);
739     } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
740                          Name == "sse41.pmaxuw" ||
741                          Name == "sse41.pmaxud" ||
742                          Name.startswith("avx2.pmaxu") ||
743                          Name.startswith("avx512.mask.pmaxu"))) {
744       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_UGT);
745     } else if (IsX86 && (Name == "sse41.pminsb" ||
746                          Name == "sse2.pmins.w" ||
747                          Name == "sse41.pminsd" ||
748                          Name.startswith("avx2.pmins") ||
749                          Name.startswith("avx512.mask.pmins"))) {
750       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SLT);
751     } else if (IsX86 && (Name == "sse2.pminu.b" ||
752                          Name == "sse41.pminuw" ||
753                          Name == "sse41.pminud" ||
754                          Name.startswith("avx2.pminu") ||
755                          Name.startswith("avx512.mask.pminu"))) {
756       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_ULT);
757     } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
758                          Name == "sse2.cvtps2pd" ||
759                          Name == "avx.cvtdq2.pd.256" ||
760                          Name == "avx.cvt.ps2.pd.256")) {
761       // Lossless i32/float to double conversion.
762       // Extract the bottom elements if necessary and convert to double vector.
763       Value *Src = CI->getArgOperand(0);
764       VectorType *SrcTy = cast<VectorType>(Src->getType());
765       VectorType *DstTy = cast<VectorType>(CI->getType());
766       Rep = CI->getArgOperand(0);
767 
768       unsigned NumDstElts = DstTy->getNumElements();
769       if (NumDstElts < SrcTy->getNumElements()) {
770         assert(NumDstElts == 2 && "Unexpected vector size");
771         uint32_t ShuffleMask[2] = { 0, 1 };
772         Rep = Builder.CreateShuffleVector(Rep, UndefValue::get(SrcTy),
773                                           ShuffleMask);
774       }
775 
776       bool Int2Double = (StringRef::npos != Name.find("cvtdq2"));
777       if (Int2Double)
778         Rep = Builder.CreateSIToFP(Rep, DstTy, "cvtdq2pd");
779       else
780         Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
781     } else if (IsX86 && Name.startswith("sse4a.movnt.")) {
782       Module *M = F->getParent();
783       SmallVector<Metadata *, 1> Elts;
784       Elts.push_back(
785           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
786       MDNode *Node = MDNode::get(C, Elts);
787 
788       Value *Arg0 = CI->getArgOperand(0);
789       Value *Arg1 = CI->getArgOperand(1);
790 
791       // Nontemporal (unaligned) store of the 0'th element of the float/double
792       // vector.
793       Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
794       PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
795       Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
796       Value *Extract =
797           Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
798 
799       StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, 1);
800       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
801 
802       // Remove intrinsic.
803       CI->eraseFromParent();
804       return;
805     } else if (IsX86 && (Name.startswith("avx.movnt.") ||
806                          Name.startswith("avx512.storent."))) {
807       Module *M = F->getParent();
808       SmallVector<Metadata *, 1> Elts;
809       Elts.push_back(
810           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
811       MDNode *Node = MDNode::get(C, Elts);
812 
813       Value *Arg0 = CI->getArgOperand(0);
814       Value *Arg1 = CI->getArgOperand(1);
815 
816       // Convert the type of the pointer to a pointer to the stored type.
817       Value *BC = Builder.CreateBitCast(Arg0,
818                                         PointerType::getUnqual(Arg1->getType()),
819                                         "cast");
820       VectorType *VTy = cast<VectorType>(Arg1->getType());
821       StoreInst *SI = Builder.CreateAlignedStore(Arg1, BC,
822                                                  VTy->getBitWidth() / 8);
823       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
824 
825       // Remove intrinsic.
826       CI->eraseFromParent();
827       return;
828     } else if (IsX86 && Name == "sse2.storel.dq") {
829       Value *Arg0 = CI->getArgOperand(0);
830       Value *Arg1 = CI->getArgOperand(1);
831 
832       Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
833       Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
834       Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
835       Value *BC = Builder.CreateBitCast(Arg0,
836                                         PointerType::getUnqual(Elt->getType()),
837                                         "cast");
838       Builder.CreateAlignedStore(Elt, BC, 1);
839 
840       // Remove intrinsic.
841       CI->eraseFromParent();
842       return;
843     } else if (IsX86 && (Name.startswith("sse.storeu.") ||
844                          Name.startswith("sse2.storeu.") ||
845                          Name.startswith("avx.storeu."))) {
846       Value *Arg0 = CI->getArgOperand(0);
847       Value *Arg1 = CI->getArgOperand(1);
848 
849       Arg0 = Builder.CreateBitCast(Arg0,
850                                    PointerType::getUnqual(Arg1->getType()),
851                                    "cast");
852       Builder.CreateAlignedStore(Arg1, Arg0, 1);
853 
854       // Remove intrinsic.
855       CI->eraseFromParent();
856       return;
857     } else if (IsX86 && (Name.startswith("avx512.mask.storeu."))) {
858       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
859                          CI->getArgOperand(2), /*Aligned*/false);
860 
861       // Remove intrinsic.
862       CI->eraseFromParent();
863       return;
864     } else if (IsX86 && (Name.startswith("avx512.mask.store."))) {
865       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
866                          CI->getArgOperand(2), /*Aligned*/true);
867 
868       // Remove intrinsic.
869       CI->eraseFromParent();
870       return;
871     } else if (IsX86 && (Name.startswith("avx512.mask.loadu."))) {
872       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
873                               CI->getArgOperand(1), CI->getArgOperand(2),
874                               /*Aligned*/false);
875     } else if (IsX86 && (Name.startswith("avx512.mask.load."))) {
876       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
877                               CI->getArgOperand(1),CI->getArgOperand(2),
878                               /*Aligned*/true);
879     } else if (IsX86 && Name.startswith("xop.vpcom")) {
880       Intrinsic::ID intID;
881       if (Name.endswith("ub"))
882         intID = Intrinsic::x86_xop_vpcomub;
883       else if (Name.endswith("uw"))
884         intID = Intrinsic::x86_xop_vpcomuw;
885       else if (Name.endswith("ud"))
886         intID = Intrinsic::x86_xop_vpcomud;
887       else if (Name.endswith("uq"))
888         intID = Intrinsic::x86_xop_vpcomuq;
889       else if (Name.endswith("b"))
890         intID = Intrinsic::x86_xop_vpcomb;
891       else if (Name.endswith("w"))
892         intID = Intrinsic::x86_xop_vpcomw;
893       else if (Name.endswith("d"))
894         intID = Intrinsic::x86_xop_vpcomd;
895       else if (Name.endswith("q"))
896         intID = Intrinsic::x86_xop_vpcomq;
897       else
898         llvm_unreachable("Unknown suffix");
899 
900       Name = Name.substr(9); // strip off "xop.vpcom"
901       unsigned Imm;
902       if (Name.startswith("lt"))
903         Imm = 0;
904       else if (Name.startswith("le"))
905         Imm = 1;
906       else if (Name.startswith("gt"))
907         Imm = 2;
908       else if (Name.startswith("ge"))
909         Imm = 3;
910       else if (Name.startswith("eq"))
911         Imm = 4;
912       else if (Name.startswith("ne"))
913         Imm = 5;
914       else if (Name.startswith("false"))
915         Imm = 6;
916       else if (Name.startswith("true"))
917         Imm = 7;
918       else
919         llvm_unreachable("Unknown condition");
920 
921       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
922       Rep =
923           Builder.CreateCall(VPCOM, {CI->getArgOperand(0), CI->getArgOperand(1),
924                                      Builder.getInt8(Imm)});
925     } else if (IsX86 && Name == "xop.vpcmov") {
926       Value *Arg0 = CI->getArgOperand(0);
927       Value *Arg1 = CI->getArgOperand(1);
928       Value *Sel = CI->getArgOperand(2);
929       unsigned NumElts = CI->getType()->getVectorNumElements();
930       Constant *MinusOne = ConstantVector::getSplat(NumElts, Builder.getInt64(-1));
931       Value *NotSel = Builder.CreateXor(Sel, MinusOne);
932       Value *Sel0 = Builder.CreateAnd(Arg0, Sel);
933       Value *Sel1 = Builder.CreateAnd(Arg1, NotSel);
934       Rep = Builder.CreateOr(Sel0, Sel1);
935     } else if (IsX86 && Name == "sse42.crc32.64.8") {
936       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
937                                                Intrinsic::x86_sse42_crc32_32_8);
938       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
939       Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
940       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
941     } else if (IsX86 && Name.startswith("avx.vbroadcast.s")) {
942       // Replace broadcasts with a series of insertelements.
943       Type *VecTy = CI->getType();
944       Type *EltTy = VecTy->getVectorElementType();
945       unsigned EltNum = VecTy->getVectorNumElements();
946       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
947                                           EltTy->getPointerTo());
948       Value *Load = Builder.CreateLoad(EltTy, Cast);
949       Type *I32Ty = Type::getInt32Ty(C);
950       Rep = UndefValue::get(VecTy);
951       for (unsigned I = 0; I < EltNum; ++I)
952         Rep = Builder.CreateInsertElement(Rep, Load,
953                                           ConstantInt::get(I32Ty, I));
954     } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
955                          Name.startswith("sse41.pmovzx") ||
956                          Name.startswith("avx2.pmovsx") ||
957                          Name.startswith("avx2.pmovzx") ||
958                          Name.startswith("avx512.mask.pmovsx") ||
959                          Name.startswith("avx512.mask.pmovzx"))) {
960       VectorType *SrcTy = cast<VectorType>(CI->getArgOperand(0)->getType());
961       VectorType *DstTy = cast<VectorType>(CI->getType());
962       unsigned NumDstElts = DstTy->getNumElements();
963 
964       // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
965       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
966       for (unsigned i = 0; i != NumDstElts; ++i)
967         ShuffleMask[i] = i;
968 
969       Value *SV = Builder.CreateShuffleVector(
970           CI->getArgOperand(0), UndefValue::get(SrcTy), ShuffleMask);
971 
972       bool DoSext = (StringRef::npos != Name.find("pmovsx"));
973       Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
974                    : Builder.CreateZExt(SV, DstTy);
975       // If there are 3 arguments, it's a masked intrinsic so we need a select.
976       if (CI->getNumArgOperands() == 3)
977         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
978                             CI->getArgOperand(1));
979     } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
980                          Name == "avx2.vbroadcasti128")) {
981       // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
982       Type *EltTy = CI->getType()->getVectorElementType();
983       unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
984       Type *VT = VectorType::get(EltTy, NumSrcElts);
985       Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
986                                             PointerType::getUnqual(VT));
987       Value *Load = Builder.CreateAlignedLoad(Op, 1);
988       if (NumSrcElts == 2)
989         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
990                                           { 0, 1, 0, 1 });
991       else
992         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
993                                           { 0, 1, 2, 3, 0, 1, 2, 3 });
994     } else if (IsX86 && (Name.startswith("avx2.pbroadcast") ||
995                          Name.startswith("avx2.vbroadcast") ||
996                          Name.startswith("avx512.pbroadcast") ||
997                          Name.startswith("avx512.mask.broadcast.s"))) {
998       // Replace vp?broadcasts with a vector shuffle.
999       Value *Op = CI->getArgOperand(0);
1000       unsigned NumElts = CI->getType()->getVectorNumElements();
1001       Type *MaskTy = VectorType::get(Type::getInt32Ty(C), NumElts);
1002       Rep = Builder.CreateShuffleVector(Op, UndefValue::get(Op->getType()),
1003                                         Constant::getNullValue(MaskTy));
1004 
1005       if (CI->getNumArgOperands() == 3)
1006         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1007                             CI->getArgOperand(1));
1008     } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
1009       Rep = UpgradeX86PALIGNRIntrinsics(Builder, CI->getArgOperand(0),
1010                                         CI->getArgOperand(1),
1011                                         CI->getArgOperand(2),
1012                                         CI->getArgOperand(3),
1013                                         CI->getArgOperand(4));
1014     } else if (IsX86 && (Name == "sse2.psll.dq" ||
1015                          Name == "avx2.psll.dq")) {
1016       // 128/256-bit shift left specified in bits.
1017       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1018       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
1019                                        Shift / 8); // Shift is in bits.
1020     } else if (IsX86 && (Name == "sse2.psrl.dq" ||
1021                          Name == "avx2.psrl.dq")) {
1022       // 128/256-bit shift right specified in bits.
1023       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1024       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
1025                                        Shift / 8); // Shift is in bits.
1026     } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
1027                          Name == "avx2.psll.dq.bs" ||
1028                          Name == "avx512.psll.dq.512")) {
1029       // 128/256/512-bit shift left specified in bytes.
1030       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1031       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
1032     } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
1033                          Name == "avx2.psrl.dq.bs" ||
1034                          Name == "avx512.psrl.dq.512")) {
1035       // 128/256/512-bit shift right specified in bytes.
1036       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1037       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
1038     } else if (IsX86 && (Name == "sse41.pblendw" ||
1039                          Name.startswith("sse41.blendp") ||
1040                          Name.startswith("avx.blend.p") ||
1041                          Name == "avx2.pblendw" ||
1042                          Name.startswith("avx2.pblendd."))) {
1043       Value *Op0 = CI->getArgOperand(0);
1044       Value *Op1 = CI->getArgOperand(1);
1045       unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1046       VectorType *VecTy = cast<VectorType>(CI->getType());
1047       unsigned NumElts = VecTy->getNumElements();
1048 
1049       SmallVector<uint32_t, 16> Idxs(NumElts);
1050       for (unsigned i = 0; i != NumElts; ++i)
1051         Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
1052 
1053       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1054     } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
1055                          Name == "avx2.vinserti128")) {
1056       Value *Op0 = CI->getArgOperand(0);
1057       Value *Op1 = CI->getArgOperand(1);
1058       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1059       VectorType *VecTy = cast<VectorType>(CI->getType());
1060       unsigned NumElts = VecTy->getNumElements();
1061 
1062       // Mask off the high bits of the immediate value; hardware ignores those.
1063       Imm = Imm & 1;
1064 
1065       // Extend the second operand into a vector that is twice as big.
1066       Value *UndefV = UndefValue::get(Op1->getType());
1067       SmallVector<uint32_t, 8> Idxs(NumElts);
1068       for (unsigned i = 0; i != NumElts; ++i)
1069         Idxs[i] = i;
1070       Rep = Builder.CreateShuffleVector(Op1, UndefV, Idxs);
1071 
1072       // Insert the second operand into the first operand.
1073 
1074       // Note that there is no guarantee that instruction lowering will actually
1075       // produce a vinsertf128 instruction for the created shuffles. In
1076       // particular, the 0 immediate case involves no lane changes, so it can
1077       // be handled as a blend.
1078 
1079       // Example of shuffle mask for 32-bit elements:
1080       // Imm = 1  <i32 0, i32 1, i32 2,  i32 3,  i32 8, i32 9, i32 10, i32 11>
1081       // Imm = 0  <i32 8, i32 9, i32 10, i32 11, i32 4, i32 5, i32 6,  i32 7 >
1082 
1083       // The low half of the result is either the low half of the 1st operand
1084       // or the low half of the 2nd operand (the inserted vector).
1085       for (unsigned i = 0; i != NumElts / 2; ++i)
1086         Idxs[i] = Imm ? i : (i + NumElts);
1087       // The high half of the result is either the low half of the 2nd operand
1088       // (the inserted vector) or the high half of the 1st operand.
1089       for (unsigned i = NumElts / 2; i != NumElts; ++i)
1090         Idxs[i] = Imm ? (i + NumElts / 2) : i;
1091       Rep = Builder.CreateShuffleVector(Op0, Rep, Idxs);
1092     } else if (IsX86 && (Name.startswith("avx.vextractf128.") ||
1093                          Name == "avx2.vextracti128")) {
1094       Value *Op0 = CI->getArgOperand(0);
1095       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1096       VectorType *VecTy = cast<VectorType>(CI->getType());
1097       unsigned NumElts = VecTy->getNumElements();
1098 
1099       // Mask off the high bits of the immediate value; hardware ignores those.
1100       Imm = Imm & 1;
1101 
1102       // Get indexes for either the high half or low half of the input vector.
1103       SmallVector<uint32_t, 4> Idxs(NumElts);
1104       for (unsigned i = 0; i != NumElts; ++i) {
1105         Idxs[i] = Imm ? (i + NumElts) : i;
1106       }
1107 
1108       Value *UndefV = UndefValue::get(Op0->getType());
1109       Rep = Builder.CreateShuffleVector(Op0, UndefV, Idxs);
1110     } else if (!IsX86 && Name == "stackprotectorcheck") {
1111       Rep = nullptr;
1112     } else if (IsX86 && (Name.startswith("avx512.mask.perm.df.") ||
1113                          Name.startswith("avx512.mask.perm.di."))) {
1114       Value *Op0 = CI->getArgOperand(0);
1115       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1116       VectorType *VecTy = cast<VectorType>(CI->getType());
1117       unsigned NumElts = VecTy->getNumElements();
1118 
1119       SmallVector<uint32_t, 8> Idxs(NumElts);
1120       for (unsigned i = 0; i != NumElts; ++i)
1121         Idxs[i] = (i & ~0x3) + ((Imm >> (2 * (i & 0x3))) & 3);
1122 
1123       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1124 
1125       if (CI->getNumArgOperands() == 4)
1126         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1127                             CI->getArgOperand(2));
1128     } else if (IsX86 && (Name.startswith("avx.vpermil.") ||
1129                          Name == "sse2.pshuf.d" ||
1130                          Name.startswith("avx512.mask.vpermil.p") ||
1131                          Name.startswith("avx512.mask.pshuf.d."))) {
1132       Value *Op0 = CI->getArgOperand(0);
1133       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1134       VectorType *VecTy = cast<VectorType>(CI->getType());
1135       unsigned NumElts = VecTy->getNumElements();
1136       // Calculate the size of each index in the immediate.
1137       unsigned IdxSize = 64 / VecTy->getScalarSizeInBits();
1138       unsigned IdxMask = ((1 << IdxSize) - 1);
1139 
1140       SmallVector<uint32_t, 8> Idxs(NumElts);
1141       // Lookup the bits for this element, wrapping around the immediate every
1142       // 8-bits. Elements are grouped into sets of 2 or 4 elements so we need
1143       // to offset by the first index of each group.
1144       for (unsigned i = 0; i != NumElts; ++i)
1145         Idxs[i] = ((Imm >> ((i * IdxSize) % 8)) & IdxMask) | (i & ~IdxMask);
1146 
1147       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1148 
1149       if (CI->getNumArgOperands() == 4)
1150         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1151                             CI->getArgOperand(2));
1152     } else if (IsX86 && (Name == "sse2.pshufl.w" ||
1153                          Name.startswith("avx512.mask.pshufl.w."))) {
1154       Value *Op0 = CI->getArgOperand(0);
1155       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1156       unsigned NumElts = CI->getType()->getVectorNumElements();
1157 
1158       SmallVector<uint32_t, 16> Idxs(NumElts);
1159       for (unsigned l = 0; l != NumElts; l += 8) {
1160         for (unsigned i = 0; i != 4; ++i)
1161           Idxs[i + l] = ((Imm >> (2 * i)) & 0x3) + l;
1162         for (unsigned i = 4; i != 8; ++i)
1163           Idxs[i + l] = i + l;
1164       }
1165 
1166       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1167 
1168       if (CI->getNumArgOperands() == 4)
1169         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1170                             CI->getArgOperand(2));
1171     } else if (IsX86 && (Name == "sse2.pshufh.w" ||
1172                          Name.startswith("avx512.mask.pshufh.w."))) {
1173       Value *Op0 = CI->getArgOperand(0);
1174       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1175       unsigned NumElts = CI->getType()->getVectorNumElements();
1176 
1177       SmallVector<uint32_t, 16> Idxs(NumElts);
1178       for (unsigned l = 0; l != NumElts; l += 8) {
1179         for (unsigned i = 0; i != 4; ++i)
1180           Idxs[i + l] = i + l;
1181         for (unsigned i = 0; i != 4; ++i)
1182           Idxs[i + l + 4] = ((Imm >> (2 * i)) & 0x3) + 4 + l;
1183       }
1184 
1185       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1186 
1187       if (CI->getNumArgOperands() == 4)
1188         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1189                             CI->getArgOperand(2));
1190     } else if (IsX86 && Name.startswith("avx512.mask.shuf.p")) {
1191       Value *Op0 = CI->getArgOperand(0);
1192       Value *Op1 = CI->getArgOperand(1);
1193       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1194       unsigned NumElts = CI->getType()->getVectorNumElements();
1195 
1196       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1197       unsigned HalfLaneElts = NumLaneElts / 2;
1198 
1199       SmallVector<uint32_t, 16> Idxs(NumElts);
1200       for (unsigned i = 0; i != NumElts; ++i) {
1201         // Base index is the starting element of the lane.
1202         Idxs[i] = i - (i % NumLaneElts);
1203         // If we are half way through the lane switch to the other source.
1204         if ((i % NumLaneElts) >= HalfLaneElts)
1205           Idxs[i] += NumElts;
1206         // Now select the specific element. By adding HalfLaneElts bits from
1207         // the immediate. Wrapping around the immediate every 8-bits.
1208         Idxs[i] += (Imm >> ((i * HalfLaneElts) % 8)) & ((1 << HalfLaneElts) - 1);
1209       }
1210 
1211       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1212 
1213       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
1214                           CI->getArgOperand(3));
1215     } else if (IsX86 && (Name.startswith("avx512.mask.movddup") ||
1216                          Name.startswith("avx512.mask.movshdup") ||
1217                          Name.startswith("avx512.mask.movsldup"))) {
1218       Value *Op0 = CI->getArgOperand(0);
1219       unsigned NumElts = CI->getType()->getVectorNumElements();
1220       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1221 
1222       unsigned Offset = 0;
1223       if (Name.startswith("avx512.mask.movshdup."))
1224         Offset = 1;
1225 
1226       SmallVector<uint32_t, 16> Idxs(NumElts);
1227       for (unsigned l = 0; l != NumElts; l += NumLaneElts)
1228         for (unsigned i = 0; i != NumLaneElts; i += 2) {
1229           Idxs[i + l + 0] = i + l + Offset;
1230           Idxs[i + l + 1] = i + l + Offset;
1231         }
1232 
1233       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1234 
1235       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1236                           CI->getArgOperand(1));
1237     } else if (IsX86 && (Name.startswith("avx512.mask.punpckl") ||
1238                          Name.startswith("avx512.mask.unpckl."))) {
1239       Value *Op0 = CI->getArgOperand(0);
1240       Value *Op1 = CI->getArgOperand(1);
1241       int NumElts = CI->getType()->getVectorNumElements();
1242       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1243 
1244       SmallVector<uint32_t, 64> Idxs(NumElts);
1245       for (int l = 0; l != NumElts; l += NumLaneElts)
1246         for (int i = 0; i != NumLaneElts; ++i)
1247           Idxs[i + l] = l + (i / 2) + NumElts * (i % 2);
1248 
1249       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1250 
1251       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1252                           CI->getArgOperand(2));
1253     } else if (IsX86 && (Name.startswith("avx512.mask.punpckh") ||
1254                          Name.startswith("avx512.mask.unpckh."))) {
1255       Value *Op0 = CI->getArgOperand(0);
1256       Value *Op1 = CI->getArgOperand(1);
1257       int NumElts = CI->getType()->getVectorNumElements();
1258       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1259 
1260       SmallVector<uint32_t, 64> Idxs(NumElts);
1261       for (int l = 0; l != NumElts; l += NumLaneElts)
1262         for (int i = 0; i != NumLaneElts; ++i)
1263           Idxs[i + l] = (NumLaneElts / 2) + l + (i / 2) + NumElts * (i % 2);
1264 
1265       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1266 
1267       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1268                           CI->getArgOperand(2));
1269     } else if (IsX86 && Name.startswith("avx512.mask.pand.")) {
1270       Rep = Builder.CreateAnd(CI->getArgOperand(0), CI->getArgOperand(1));
1271       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1272                           CI->getArgOperand(2));
1273     } else if (IsX86 && Name.startswith("avx512.mask.pandn.")) {
1274       Rep = Builder.CreateAnd(Builder.CreateNot(CI->getArgOperand(0)),
1275                               CI->getArgOperand(1));
1276       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1277                           CI->getArgOperand(2));
1278     } else if (IsX86 && Name.startswith("avx512.mask.por.")) {
1279       Rep = Builder.CreateOr(CI->getArgOperand(0), CI->getArgOperand(1));
1280       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1281                           CI->getArgOperand(2));
1282     } else if (IsX86 && Name.startswith("avx512.mask.pxor.")) {
1283       Rep = Builder.CreateXor(CI->getArgOperand(0), CI->getArgOperand(1));
1284       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1285                           CI->getArgOperand(2));
1286     } else if (IsX86 && Name.startswith("avx512.mask.and.")) {
1287       VectorType *FTy = cast<VectorType>(CI->getType());
1288       VectorType *ITy = VectorType::getInteger(FTy);
1289       Rep = Builder.CreateAnd(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
1290                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
1291       Rep = Builder.CreateBitCast(Rep, FTy);
1292       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1293                           CI->getArgOperand(2));
1294     } else if (IsX86 && Name.startswith("avx512.mask.andn.")) {
1295       VectorType *FTy = cast<VectorType>(CI->getType());
1296       VectorType *ITy = VectorType::getInteger(FTy);
1297       Rep = Builder.CreateNot(Builder.CreateBitCast(CI->getArgOperand(0), ITy));
1298       Rep = Builder.CreateAnd(Rep,
1299                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
1300       Rep = Builder.CreateBitCast(Rep, FTy);
1301       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1302                           CI->getArgOperand(2));
1303     } else if (IsX86 && Name.startswith("avx512.mask.or.")) {
1304       VectorType *FTy = cast<VectorType>(CI->getType());
1305       VectorType *ITy = VectorType::getInteger(FTy);
1306       Rep = Builder.CreateOr(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
1307                              Builder.CreateBitCast(CI->getArgOperand(1), ITy));
1308       Rep = Builder.CreateBitCast(Rep, FTy);
1309       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1310                           CI->getArgOperand(2));
1311     } else if (IsX86 && Name.startswith("avx512.mask.xor.")) {
1312       VectorType *FTy = cast<VectorType>(CI->getType());
1313       VectorType *ITy = VectorType::getInteger(FTy);
1314       Rep = Builder.CreateXor(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
1315                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
1316       Rep = Builder.CreateBitCast(Rep, FTy);
1317       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1318                           CI->getArgOperand(2));
1319     } else if (IsX86 && Name.startswith("avx512.mask.padd.")) {
1320       Rep = Builder.CreateAdd(CI->getArgOperand(0), CI->getArgOperand(1));
1321       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1322                           CI->getArgOperand(2));
1323     } else if (IsX86 && Name.startswith("avx512.mask.psub.")) {
1324       Rep = Builder.CreateSub(CI->getArgOperand(0), CI->getArgOperand(1));
1325       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1326                           CI->getArgOperand(2));
1327     } else if (IsX86 && Name.startswith("avx512.mask.pmull.")) {
1328       Rep = Builder.CreateMul(CI->getArgOperand(0), CI->getArgOperand(1));
1329       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1330                           CI->getArgOperand(2));
1331     } else if (IsX86 && (Name.startswith("avx512.mask.add.p"))) {
1332       Rep = Builder.CreateFAdd(CI->getArgOperand(0), CI->getArgOperand(1));
1333       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1334                           CI->getArgOperand(2));
1335     } else if (IsX86 && Name.startswith("avx512.mask.div.p")) {
1336       Rep = Builder.CreateFDiv(CI->getArgOperand(0), CI->getArgOperand(1));
1337       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1338                           CI->getArgOperand(2));
1339     } else if (IsX86 && Name.startswith("avx512.mask.mul.p")) {
1340       Rep = Builder.CreateFMul(CI->getArgOperand(0), CI->getArgOperand(1));
1341       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1342                           CI->getArgOperand(2));
1343     } else if (IsX86 && Name.startswith("avx512.mask.sub.p")) {
1344       Rep = Builder.CreateFSub(CI->getArgOperand(0), CI->getArgOperand(1));
1345       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1346                           CI->getArgOperand(2));
1347     } else if (IsX86 && Name.startswith("avx512.mask.pshuf.b.")) {
1348       VectorType *VecTy = cast<VectorType>(CI->getType());
1349       Intrinsic::ID IID;
1350       if (VecTy->getPrimitiveSizeInBits() == 128)
1351         IID = Intrinsic::x86_ssse3_pshuf_b_128;
1352       else if (VecTy->getPrimitiveSizeInBits() == 256)
1353         IID = Intrinsic::x86_avx2_pshuf_b;
1354       else
1355         llvm_unreachable("Unexpected intrinsic");
1356 
1357       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
1358                                { CI->getArgOperand(0), CI->getArgOperand(1) });
1359       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1360                           CI->getArgOperand(2));
1361     } else if (IsX86 && Name.startswith("avx512.mask.psll")) {
1362       bool IsImmediate = Name[16] == 'i' ||
1363                          (Name.size() > 18 && Name[18] == 'i');
1364       bool IsVariable = Name[16] == 'v';
1365       char Size = Name[16] == '.' ? Name[17] :
1366                   Name[17] == '.' ? Name[18] :
1367                                     Name[19];
1368 
1369       Intrinsic::ID IID;
1370       if (IsVariable && Name[17] != '.') {
1371         if (Size == 'd' && Name[17] == '2') // avx512.mask.psllv2.di
1372           IID = Intrinsic::x86_avx2_psllv_q;
1373         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psllv4.di
1374           IID = Intrinsic::x86_avx2_psllv_q_256;
1375         else if (Size == 's' && Name[17] == '4') // avx512.mask.psllv4.si
1376           IID = Intrinsic::x86_avx2_psllv_d;
1377         else if (Size == 's' && Name[17] == '8') // avx512.mask.psllv8.si
1378           IID = Intrinsic::x86_avx2_psllv_d_256;
1379         else
1380           llvm_unreachable("Unexpected size");
1381       } else if (Name.endswith(".128")) {
1382         if (Size == 'd') // avx512.mask.psll.d.128, avx512.mask.psll.di.128
1383           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_d
1384                             : Intrinsic::x86_sse2_psll_d;
1385         else if (Size == 'q') // avx512.mask.psll.q.128, avx512.mask.psll.qi.128
1386           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_q
1387                             : Intrinsic::x86_sse2_psll_q;
1388         else if (Size == 'w') // avx512.mask.psll.w.128, avx512.mask.psll.wi.128
1389           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_w
1390                             : Intrinsic::x86_sse2_psll_w;
1391         else
1392           llvm_unreachable("Unexpected size");
1393       } else if (Name.endswith(".256")) {
1394         if (Size == 'd') // avx512.mask.psll.d.256, avx512.mask.psll.di.256
1395           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_d
1396                             : Intrinsic::x86_avx2_psll_d;
1397         else if (Size == 'q') // avx512.mask.psll.q.256, avx512.mask.psll.qi.256
1398           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_q
1399                             : Intrinsic::x86_avx2_psll_q;
1400         else if (Size == 'w') // avx512.mask.psll.w.256, avx512.mask.psll.wi.256
1401           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_w
1402                             : Intrinsic::x86_avx2_psll_w;
1403         else
1404           llvm_unreachable("Unexpected size");
1405       } else {
1406         if (Size == 'd') // psll.di.512, pslli.d, psll.d, psllv.d.512
1407           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_d_512 :
1408                 IsVariable  ? Intrinsic::x86_avx512_psllv_d_512 :
1409                               Intrinsic::x86_avx512_psll_d_512;
1410         else if (Size == 'q') // psll.qi.512, pslli.q, psll.q, psllv.q.512
1411           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_q_512 :
1412                 IsVariable  ? Intrinsic::x86_avx512_psllv_q_512 :
1413                               Intrinsic::x86_avx512_psll_q_512;
1414         else if (Size == 'w') // psll.wi.512, pslli.w, psll.w
1415           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_w_512
1416                             : Intrinsic::x86_avx512_psll_w_512;
1417         else
1418           llvm_unreachable("Unexpected size");
1419       }
1420 
1421       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
1422     } else if (IsX86 && Name.startswith("avx512.mask.psrl")) {
1423       bool IsImmediate = Name[16] == 'i' ||
1424                          (Name.size() > 18 && Name[18] == 'i');
1425       bool IsVariable = Name[16] == 'v';
1426       char Size = Name[16] == '.' ? Name[17] :
1427                   Name[17] == '.' ? Name[18] :
1428                                     Name[19];
1429 
1430       Intrinsic::ID IID;
1431       if (IsVariable && Name[17] != '.') {
1432         if (Size == 'd' && Name[17] == '2') // avx512.mask.psrlv2.di
1433           IID = Intrinsic::x86_avx2_psrlv_q;
1434         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psrlv4.di
1435           IID = Intrinsic::x86_avx2_psrlv_q_256;
1436         else if (Size == 's' && Name[17] == '4') // avx512.mask.psrlv4.si
1437           IID = Intrinsic::x86_avx2_psrlv_d;
1438         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrlv8.si
1439           IID = Intrinsic::x86_avx2_psrlv_d_256;
1440         else
1441           llvm_unreachable("Unexpected size");
1442       } else if (Name.endswith(".128")) {
1443         if (Size == 'd') // avx512.mask.psrl.d.128, avx512.mask.psrl.di.128
1444           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_d
1445                             : Intrinsic::x86_sse2_psrl_d;
1446         else if (Size == 'q') // avx512.mask.psrl.q.128, avx512.mask.psrl.qi.128
1447           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_q
1448                             : Intrinsic::x86_sse2_psrl_q;
1449         else if (Size == 'w') // avx512.mask.psrl.w.128, avx512.mask.psrl.wi.128
1450           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_w
1451                             : Intrinsic::x86_sse2_psrl_w;
1452         else
1453           llvm_unreachable("Unexpected size");
1454       } else if (Name.endswith(".256")) {
1455         if (Size == 'd') // avx512.mask.psrl.d.256, avx512.mask.psrl.di.256
1456           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_d
1457                             : Intrinsic::x86_avx2_psrl_d;
1458         else if (Size == 'q') // avx512.mask.psrl.q.256, avx512.mask.psrl.qi.256
1459           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_q
1460                             : Intrinsic::x86_avx2_psrl_q;
1461         else if (Size == 'w') // avx512.mask.psrl.w.256, avx512.mask.psrl.wi.256
1462           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_w
1463                             : Intrinsic::x86_avx2_psrl_w;
1464         else
1465           llvm_unreachable("Unexpected size");
1466       } else {
1467         if (Size == 'd') // psrl.di.512, psrli.d, psrl.d, psrl.d.512
1468           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_d_512 :
1469                 IsVariable  ? Intrinsic::x86_avx512_psrlv_d_512 :
1470                               Intrinsic::x86_avx512_psrl_d_512;
1471         else if (Size == 'q') // psrl.qi.512, psrli.q, psrl.q, psrl.q.512
1472           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_q_512 :
1473                 IsVariable  ? Intrinsic::x86_avx512_psrlv_q_512 :
1474                               Intrinsic::x86_avx512_psrl_q_512;
1475         else if (Size == 'w') // psrl.wi.512, psrli.w, psrl.w)
1476           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_w_512
1477                             : Intrinsic::x86_avx512_psrl_w_512;
1478         else
1479           llvm_unreachable("Unexpected size");
1480       }
1481 
1482       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
1483     } else if (IsX86 && Name.startswith("avx512.mask.psra")) {
1484       bool IsImmediate = Name[16] == 'i' ||
1485                          (Name.size() > 18 && Name[18] == 'i');
1486       bool IsVariable = Name[16] == 'v';
1487       char Size = Name[16] == '.' ? Name[17] :
1488                   Name[17] == '.' ? Name[18] :
1489                                     Name[19];
1490 
1491       Intrinsic::ID IID;
1492       if (IsVariable && Name[17] != '.') {
1493         if (Size == 's' && Name[17] == '4') // avx512.mask.psrav4.si
1494           IID = Intrinsic::x86_avx2_psrav_d;
1495         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrav8.si
1496           IID = Intrinsic::x86_avx2_psrav_d_256;
1497         else
1498           llvm_unreachable("Unexpected size");
1499       } else if (Name.endswith(".128")) {
1500         if (Size == 'd') // avx512.mask.psra.d.128, avx512.mask.psra.di.128
1501           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_d
1502                             : Intrinsic::x86_sse2_psra_d;
1503         else if (Size == 'q') // avx512.mask.psra.q.128, avx512.mask.psra.qi.128
1504           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_128 :
1505                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_128 :
1506                               Intrinsic::x86_avx512_psra_q_128;
1507         else if (Size == 'w') // avx512.mask.psra.w.128, avx512.mask.psra.wi.128
1508           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_w
1509                             : Intrinsic::x86_sse2_psra_w;
1510         else
1511           llvm_unreachable("Unexpected size");
1512       } else if (Name.endswith(".256")) {
1513         if (Size == 'd') // avx512.mask.psra.d.256, avx512.mask.psra.di.256
1514           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_d
1515                             : Intrinsic::x86_avx2_psra_d;
1516         else if (Size == 'q') // avx512.mask.psra.q.256, avx512.mask.psra.qi.256
1517           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_256 :
1518                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_256 :
1519                               Intrinsic::x86_avx512_psra_q_256;
1520         else if (Size == 'w') // avx512.mask.psra.w.256, avx512.mask.psra.wi.256
1521           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_w
1522                             : Intrinsic::x86_avx2_psra_w;
1523         else
1524           llvm_unreachable("Unexpected size");
1525       } else {
1526         if (Size == 'd') // psra.di.512, psrai.d, psra.d, psrav.d.512
1527           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_d_512 :
1528                 IsVariable  ? Intrinsic::x86_avx512_psrav_d_512 :
1529                               Intrinsic::x86_avx512_psra_d_512;
1530         else if (Size == 'q') // psra.qi.512, psrai.q, psra.q
1531           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_512 :
1532                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_512 :
1533                               Intrinsic::x86_avx512_psra_q_512;
1534         else if (Size == 'w') // psra.wi.512, psrai.w, psra.w
1535           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_w_512
1536                             : Intrinsic::x86_avx512_psra_w_512;
1537         else
1538           llvm_unreachable("Unexpected size");
1539       }
1540 
1541       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
1542     } else {
1543       llvm_unreachable("Unknown function for CallInst upgrade.");
1544     }
1545 
1546     if (Rep)
1547       CI->replaceAllUsesWith(Rep);
1548     CI->eraseFromParent();
1549     return;
1550   }
1551 
1552   std::string Name = CI->getName();
1553   if (!Name.empty())
1554     CI->setName(Name + ".old");
1555 
1556   switch (NewFn->getIntrinsicID()) {
1557   default:
1558     llvm_unreachable("Unknown function for CallInst upgrade.");
1559 
1560   case Intrinsic::arm_neon_vld1:
1561   case Intrinsic::arm_neon_vld2:
1562   case Intrinsic::arm_neon_vld3:
1563   case Intrinsic::arm_neon_vld4:
1564   case Intrinsic::arm_neon_vld2lane:
1565   case Intrinsic::arm_neon_vld3lane:
1566   case Intrinsic::arm_neon_vld4lane:
1567   case Intrinsic::arm_neon_vst1:
1568   case Intrinsic::arm_neon_vst2:
1569   case Intrinsic::arm_neon_vst3:
1570   case Intrinsic::arm_neon_vst4:
1571   case Intrinsic::arm_neon_vst2lane:
1572   case Intrinsic::arm_neon_vst3lane:
1573   case Intrinsic::arm_neon_vst4lane: {
1574     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
1575                                  CI->arg_operands().end());
1576     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, Args));
1577     CI->eraseFromParent();
1578     return;
1579   }
1580 
1581   case Intrinsic::ctlz:
1582   case Intrinsic::cttz:
1583     assert(CI->getNumArgOperands() == 1 &&
1584            "Mismatch between function args and call args");
1585     CI->replaceAllUsesWith(Builder.CreateCall(
1586         NewFn, {CI->getArgOperand(0), Builder.getFalse()}, Name));
1587     CI->eraseFromParent();
1588     return;
1589 
1590   case Intrinsic::objectsize:
1591     CI->replaceAllUsesWith(Builder.CreateCall(
1592         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1)}, Name));
1593     CI->eraseFromParent();
1594     return;
1595 
1596   case Intrinsic::ctpop: {
1597     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, {CI->getArgOperand(0)}));
1598     CI->eraseFromParent();
1599     return;
1600   }
1601 
1602   case Intrinsic::x86_xop_vfrcz_ss:
1603   case Intrinsic::x86_xop_vfrcz_sd:
1604     CI->replaceAllUsesWith(
1605         Builder.CreateCall(NewFn, {CI->getArgOperand(1)}, Name));
1606     CI->eraseFromParent();
1607     return;
1608 
1609   case Intrinsic::x86_xop_vpermil2pd:
1610   case Intrinsic::x86_xop_vpermil2ps:
1611   case Intrinsic::x86_xop_vpermil2pd_256:
1612   case Intrinsic::x86_xop_vpermil2ps_256: {
1613     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
1614                                  CI->arg_operands().end());
1615     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
1616     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
1617     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
1618     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, Args, Name));
1619     CI->eraseFromParent();
1620     return;
1621   }
1622 
1623   case Intrinsic::x86_sse41_ptestc:
1624   case Intrinsic::x86_sse41_ptestz:
1625   case Intrinsic::x86_sse41_ptestnzc: {
1626     // The arguments for these intrinsics used to be v4f32, and changed
1627     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
1628     // So, the only thing required is a bitcast for both arguments.
1629     // First, check the arguments have the old type.
1630     Value *Arg0 = CI->getArgOperand(0);
1631     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
1632       return;
1633 
1634     // Old intrinsic, add bitcasts
1635     Value *Arg1 = CI->getArgOperand(1);
1636 
1637     Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
1638 
1639     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
1640     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
1641 
1642     CallInst *NewCall = Builder.CreateCall(NewFn, {BC0, BC1}, Name);
1643     CI->replaceAllUsesWith(NewCall);
1644     CI->eraseFromParent();
1645     return;
1646   }
1647 
1648   case Intrinsic::x86_sse41_insertps:
1649   case Intrinsic::x86_sse41_dppd:
1650   case Intrinsic::x86_sse41_dpps:
1651   case Intrinsic::x86_sse41_mpsadbw:
1652   case Intrinsic::x86_avx_dp_ps_256:
1653   case Intrinsic::x86_avx2_mpsadbw: {
1654     // Need to truncate the last argument from i32 to i8 -- this argument models
1655     // an inherently 8-bit immediate operand to these x86 instructions.
1656     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
1657                                  CI->arg_operands().end());
1658 
1659     // Replace the last argument with a trunc.
1660     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
1661 
1662     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
1663     CI->replaceAllUsesWith(NewCall);
1664     CI->eraseFromParent();
1665     return;
1666   }
1667 
1668   case Intrinsic::thread_pointer: {
1669     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, {}));
1670     CI->eraseFromParent();
1671     return;
1672   }
1673 
1674   case Intrinsic::invariant_start:
1675   case Intrinsic::invariant_end:
1676   case Intrinsic::masked_load:
1677   case Intrinsic::masked_store: {
1678     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
1679                                  CI->arg_operands().end());
1680     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, Args));
1681     CI->eraseFromParent();
1682     return;
1683   }
1684   }
1685 }
1686 
1687 void llvm::UpgradeCallsToIntrinsic(Function *F) {
1688   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
1689 
1690   // Check if this function should be upgraded and get the replacement function
1691   // if there is one.
1692   Function *NewFn;
1693   if (UpgradeIntrinsicFunction(F, NewFn)) {
1694     // Replace all users of the old function with the new function or new
1695     // instructions. This is not a range loop because the call is deleted.
1696     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
1697       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
1698         UpgradeIntrinsicCall(CI, NewFn);
1699 
1700     // Remove old function, no longer used, from the module.
1701     F->eraseFromParent();
1702   }
1703 }
1704 
1705 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
1706   // Check if the tag uses struct-path aware TBAA format.
1707   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
1708     return &MD;
1709 
1710   auto &Context = MD.getContext();
1711   if (MD.getNumOperands() == 3) {
1712     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
1713     MDNode *ScalarType = MDNode::get(Context, Elts);
1714     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
1715     Metadata *Elts2[] = {ScalarType, ScalarType,
1716                          ConstantAsMetadata::get(
1717                              Constant::getNullValue(Type::getInt64Ty(Context))),
1718                          MD.getOperand(2)};
1719     return MDNode::get(Context, Elts2);
1720   }
1721   // Create a MDNode <MD, MD, offset 0>
1722   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
1723                                     Type::getInt64Ty(Context)))};
1724   return MDNode::get(Context, Elts);
1725 }
1726 
1727 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
1728                                       Instruction *&Temp) {
1729   if (Opc != Instruction::BitCast)
1730     return nullptr;
1731 
1732   Temp = nullptr;
1733   Type *SrcTy = V->getType();
1734   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
1735       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
1736     LLVMContext &Context = V->getContext();
1737 
1738     // We have no information about target data layout, so we assume that
1739     // the maximum pointer size is 64bit.
1740     Type *MidTy = Type::getInt64Ty(Context);
1741     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
1742 
1743     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
1744   }
1745 
1746   return nullptr;
1747 }
1748 
1749 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
1750   if (Opc != Instruction::BitCast)
1751     return nullptr;
1752 
1753   Type *SrcTy = C->getType();
1754   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
1755       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
1756     LLVMContext &Context = C->getContext();
1757 
1758     // We have no information about target data layout, so we assume that
1759     // the maximum pointer size is 64bit.
1760     Type *MidTy = Type::getInt64Ty(Context);
1761 
1762     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
1763                                      DestTy);
1764   }
1765 
1766   return nullptr;
1767 }
1768 
1769 /// Check the debug info version number, if it is out-dated, drop the debug
1770 /// info. Return true if module is modified.
1771 bool llvm::UpgradeDebugInfo(Module &M) {
1772   unsigned Version = getDebugMetadataVersionFromModule(M);
1773   if (Version == DEBUG_METADATA_VERSION)
1774     return false;
1775 
1776   bool RetCode = StripDebugInfo(M);
1777   if (RetCode) {
1778     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
1779     M.getContext().diagnose(DiagVersion);
1780   }
1781   return RetCode;
1782 }
1783 
1784 bool llvm::UpgradeModuleFlags(Module &M) {
1785   const NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
1786   if (!ModFlags)
1787     return false;
1788 
1789   bool HasObjCFlag = false, HasClassProperties = false;
1790   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
1791     MDNode *Op = ModFlags->getOperand(I);
1792     if (Op->getNumOperands() < 2)
1793       continue;
1794     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1795     if (!ID)
1796       continue;
1797     if (ID->getString() == "Objective-C Image Info Version")
1798       HasObjCFlag = true;
1799     if (ID->getString() == "Objective-C Class Properties")
1800       HasClassProperties = true;
1801   }
1802   // "Objective-C Class Properties" is recently added for Objective-C. We
1803   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
1804   // flag of value 0, so we can correclty downgrade this flag when trying to
1805   // link an ObjC bitcode without this module flag with an ObjC bitcode with
1806   // this module flag.
1807   if (HasObjCFlag && !HasClassProperties) {
1808     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
1809                     (uint32_t)0);
1810     return true;
1811   }
1812   return false;
1813 }
1814 
1815 static bool isOldLoopArgument(Metadata *MD) {
1816   auto *T = dyn_cast_or_null<MDTuple>(MD);
1817   if (!T)
1818     return false;
1819   if (T->getNumOperands() < 1)
1820     return false;
1821   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
1822   if (!S)
1823     return false;
1824   return S->getString().startswith("llvm.vectorizer.");
1825 }
1826 
1827 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
1828   StringRef OldPrefix = "llvm.vectorizer.";
1829   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
1830 
1831   if (OldTag == "llvm.vectorizer.unroll")
1832     return MDString::get(C, "llvm.loop.interleave.count");
1833 
1834   return MDString::get(
1835       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
1836              .str());
1837 }
1838 
1839 static Metadata *upgradeLoopArgument(Metadata *MD) {
1840   auto *T = dyn_cast_or_null<MDTuple>(MD);
1841   if (!T)
1842     return MD;
1843   if (T->getNumOperands() < 1)
1844     return MD;
1845   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
1846   if (!OldTag)
1847     return MD;
1848   if (!OldTag->getString().startswith("llvm.vectorizer."))
1849     return MD;
1850 
1851   // This has an old tag.  Upgrade it.
1852   SmallVector<Metadata *, 8> Ops;
1853   Ops.reserve(T->getNumOperands());
1854   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
1855   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
1856     Ops.push_back(T->getOperand(I));
1857 
1858   return MDTuple::get(T->getContext(), Ops);
1859 }
1860 
1861 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
1862   auto *T = dyn_cast<MDTuple>(&N);
1863   if (!T)
1864     return &N;
1865 
1866   if (none_of(T->operands(), isOldLoopArgument))
1867     return &N;
1868 
1869   SmallVector<Metadata *, 8> Ops;
1870   Ops.reserve(T->getNumOperands());
1871   for (Metadata *MD : T->operands())
1872     Ops.push_back(upgradeLoopArgument(MD));
1873 
1874   return MDTuple::get(T->getContext(), Ops);
1875 }
1876