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