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